Suppose
array contains elements like {2, 3, 4, 5, 1, 1, 3, 10, 2, 12} then the
duplicate elements are {1, 3, and 2} (Return the duplicate elements as they
appeared in the array).
We can solve
this problem by using HashMap and List, traverse array and insert elements into
hashmap and increase the count of elements every time. If element count is 2,
then add the element to list, else do nothing.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class UniqueElements { public static List<Integer> findUniqueElements(int arr[]) { Objects.nonNull(arr); List<Integer> result = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<>(); for (int key : arr) { if (map.containsKey(key)) { int val = map.get(key); map.put(key, val + 1); if (val == 1) result.add(key); } else { map.put(key, 1); } } return result; } }
Following is
the junit test case for above program.
import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; public class UniqueElementsTest { @Test public void test1() { int arr1[] = { 2, 1, 2, 4, 3, 1, 5, 1 }; int arr2[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 2, 3, 4, 5 }; int arr3[] = {2, 3, 4, 5, 1, 1, 3, 10, 2, 12}; List<Integer> actual1 = UniqueElements.findUniqueElements(arr1); List<Integer> actual2 = UniqueElements.findUniqueElements(arr2); List<Integer> actual3 = UniqueElements.findUniqueElements(arr3); List<Integer> expected1 = Arrays.asList(2, 1); List<Integer> expected2 = Arrays.asList(5, 4, 3, 2, 1); List<Integer> expected3 = Arrays.asList(1, 3, 2); assertTrue(actual1.equals(expected1)); assertTrue(actual2.equals(expected2)); assertTrue(actual3.equals(expected3)); } @Test(expected = NullPointerException.class) public void test2() { UniqueElements.findUniqueElements(null); } }
No comments:
Post a Comment