Input: nums =[0,1,2,2,4,4,1]Output: 2Explanation:
The even elements are 0,2, and 4. Of these,2 and 4 appear the most.We return the smallest one, which is2.
Count the frequency of each even element. The answer is the even element with the highest frequency; if there is a tie, return the smallest one. If no even element exists, return -1.
import java.util.*;
classSolution {
publicintmostFrequentEven(int[] nums) {
Map<Integer, Integer> count =new HashMap<>();
for (int x : nums) {
if (x % 2 == 0) count.put(x, count.getOrDefault(x, 0) + 1);
}
int ans =-1, max = 0;
for (int k : count.keySet()) {
int v = count.get(k);
if (v > max || (v == max && k < ans) || ans ==-1) {
max = v;
ans = k;
}
}
return ans;
}
}
1
2
3
4
5
6
7
defmostFrequentEven(nums):
from collections import Counter
count = Counter(x for x in nums if x %2==0)
ifnot count:
return-1 max_freq = max(count.values())
return min(x for x in count if count[x] == max_freq)