[LeetCode] Most Frequent Even Element

2404. Most Frequent Even Element

Given an integer array nums, return the most frequent even element.

If there is a tie, return the smallest one. If there is no such element, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int mostFrequentEven(vector<int>& nums) {
unordered_map<int,int> freq;
int ma = -1, res = -1;
for(auto& n : nums) {
if(n & 1) continue;
freq[n]++;
if(freq[n] > ma) {
ma = freq[n];
res = n;
} else if(freq[n] == ma) {
res = min(res, n);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/11/PS/LeetCode/most-frequent-even-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.