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
.
Input: nums = [0,1,2,2,4,4,1] Output: 2 Explanation: The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We return the smallest one, which is 2.
Input: nums = [4,4,4,9,2,4] Output: 4 Explanation: 4 is the even element appears the most.
Input: nums = [29,47,21,41,13,37,25,7] Output: -1 Explanation: There is no even element.
1 <= nums.length <= 2000
0 <= nums[i] <= 105
use std::collections::HashMap;
impl Solution {
pub fn most_frequent_even(nums: Vec<i32>) -> i32 {
let mut count = HashMap::new();
let mut max_count = 0;
let mut ret = -1;
for num in nums.iter().filter(|&&x| x % 2 == 0) {
count.entry(num).and_modify(|x| *x += 1).or_insert(1);
}
for (&k, v) in count {
if v > max_count || (v == max_count && k < ret) {
max_count = v;
ret = k;
}
}
ret
}
}