Skip to content

Latest commit

 

History

History
62 lines (57 loc) · 2.27 KB

README.md

File metadata and controls

62 lines (57 loc) · 2.27 KB

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.

 

Example 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.

Example 2:

Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: 4 is the even element appears the most.

Example 3:

Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: There is no even element.

 

Constraints:

  • 1 <= nums.length <= 2000
  • 0 <= nums[i] <= 105

Related Topics:
Array, Hash Table, Counting

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/most-frequent-even-element
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int mostFrequentEven(vector<int>& A) {
        unordered_map<int, int> cnt;
        for (int n : A) {
            if (n % 2 == 0) cnt[n]++;
        }
        int maxFreq = 0, ans = -1;
        for (auto &[n, c] : cnt) {
            if (c > maxFreq) {
                ans = n;
                maxFreq = c;
            } else if (c == maxFreq && n < ans) ans = n;
        }
        return ans;
    }
};