LeetCode 题解工作台
出现最频繁的偶数元素
给你一个整数数组 nums ,返回出现最频繁的偶数元素。 如果存在多个满足条件的元素,只需要返回 最小 的一个。如果不存在这样的元素,返回 -1 。 示例 1: 输入: nums = [0,1,2,2,4,4,1] 输出: 2 解释: 数组中的偶数元素为 0、2 和 4 ,在这些元素中,2 和 4 …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用哈希表 统计所有偶数元素出现的次数,然后找出出现次数最多且值最小的偶数元素。 时间复杂度 ,空间复杂度 。其中 是数组的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums ,返回出现最频繁的偶数元素。
如果存在多个满足条件的元素,只需要返回 最小 的一个。如果不存在这样的元素,返回 -1 。
示例 1:
输入:nums = [0,1,2,2,4,4,1] 输出:2 解释: 数组中的偶数元素为 0、2 和 4 ,在这些元素中,2 和 4 出现次数最多。 返回最小的那个,即返回 2 。
示例 2:
输入:nums = [4,4,4,9,2,4] 输出:4 解释:4 是出现最频繁的偶数元素。
示例 3:
输入:nums = [29,47,21,41,13,37,25,7] 输出:-1 解释:不存在偶数元素。
提示:
1 <= nums.length <= 20000 <= nums[i] <= 105
解题思路
方法一:哈希表
我们用哈希表 统计所有偶数元素出现的次数,然后找出出现次数最多且值最小的偶数元素。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
cnt = Counter(x for x in nums if x % 2 == 0)
ans, mx = -1, 0
for x, v in cnt.items():
if v > mx or (v == mx and ans > x):
ans, mx = x, v
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for scanning the array and updating the hash table. Space complexity is O(n) in the worst case if all elements are even and distinct, due to storing counts in the hash table. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask if you can count frequencies instead of sorting to optimize performance.
- question_mark
Check how you handle ties and whether the smallest element is returned.
- question_mark
Consider edge cases with no even numbers to ensure robust solution.
常见陷阱
外企场景- error
Forgetting to filter for even numbers before counting can lead to wrong results.
- error
Neglecting the tie-breaker rule can cause failing outputs when frequencies match.
- error
Returning 0 instead of -1 when no even numbers exist is a common oversight.
进阶变体
外企场景- arrow_right_alt
Most Frequent Odd Element: same pattern but filter for odd numbers instead.
- arrow_right_alt
Most Frequent Element Overall: count all elements without parity filtering.
- arrow_right_alt
Top K Frequent Even Elements: extend hash table to track top K frequencies instead of one.