Given an integer array, where exactly one element occurs an even number of times and all others occur an odd number of times, find the element with even occurrences.
import java.util.*;
classSolution {
publicintfindEven(int[] arr) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : arr) freq.put(x, freq.getOrDefault(x, 0) + 1);
for (var entry : freq.entrySet())
if (entry.getValue() % 2 == 0) return entry.getKey();
return-1;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffindEven(self, arr: list[int]) -> int:
freq: dict[int, int] = {}
for x in arr:
freq[x] = freq.get(x, 0) +1for num, cnt in freq.items():
if cnt %2==0:
return num
return-1