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
Solution: Hashtable
Use a hashtable to store the frequency of even numbers.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: int mostFrequentEven(vector<int>& nums) { unordered_map<int, int> m; int ans = -1; int best = 0; for (int x : nums) { if (x & 1) continue; int cur = ++m[x]; if (cur > best) { best = cur; ans = x; } else if (cur == best && x < ans) { ans = x; } } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment