forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2404.java
36 lines (34 loc) · 1.12 KB
/
_2404.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class _2404 {
public static class Solution1 {
public int mostFrequentEven(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
}
List<Integer> smallestEvens = new ArrayList<>();
int freq = 0;
for (int key : map.keySet()) {
if (map.get(key) > freq) {
smallestEvens.clear();
freq = map.get(key);
smallestEvens.add(key);
} else if (map.get(key) == freq) {
smallestEvens.add(key);
}
}
if (smallestEvens.size() < 1) {
return -1;
}
Collections.sort(smallestEvens);
return smallestEvens.get(0);
}
}
}