Given an
array, find the first element that appears an even number of times.
import java.util.LinkedHashMap; import java.util.Objects; import java.util.Optional; import java.util.Set; public class ArrayUtil { public static Optional<Integer> getFirstEvenNumber(int[] arr) { if (Objects.isNull(arr)) throw new NullPointerException("Array Shouldn't be null"); LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>(); for (int data : arr) { if (!map.containsKey(data)) { map.put(data, 1); continue; } map.put(data, map.get(data) + 1); } Set<Integer> keys = map.keySet(); for (int key : keys) { if (map.get(key) % 2 == 0) { return Optional.of(key); } } return Optional.empty(); } }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ArrayUtilTest { @Test public void test() { int arr1[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 3, 2 }; int arr2[] = {}; int arr3[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 3, 2, 4 }; int arr4[] = { 1, 2, 3, 4, 4, 3, 2, 1 }; int arr5[] = {5, 1, 2, 3, 4, 4, 3, 2, 1, 5}; int result1 = ArrayUtil.getFirstEvenNumber(arr1).get(); int result4 = ArrayUtil.getFirstEvenNumber(arr4).get(); int result5 = ArrayUtil.getFirstEvenNumber(arr5).get(); assertEquals(result1, 4); if (!ArrayUtil.getFirstEvenNumber(arr2).isPresent()) { assertTrue(true); } else { assertTrue(false); } if (!ArrayUtil.getFirstEvenNumber(arr3).isPresent()) { assertTrue(true); } else { assertTrue(false); } assertEquals(result4, 1); assertEquals(result5, 5); } }
No comments:
Post a Comment