LeetCode 题解工作台

出现最频繁的偶数元素

给你一个整数数组 nums ,返回出现最频繁的偶数元素。 如果存在多个满足条件的元素,只需要返回 最小 的一个。如果不存在这样的元素,返回 -1 。 示例 1: 输入: nums = [0,1,2,2,4,4,1] 输出: 2 解释: 数组中的偶数元素为 0、2 和 4 ,在这些元素中,2 和 4 …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们用哈希表 统计所有偶数元素出现的次数,然后找出出现次数最多且值最小的偶数元素。 时间复杂度 ,空间复杂度 。其中 是数组的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 2000
  • 0 <= nums[i] <= 105
lightbulb

解题思路

方法一:哈希表

我们用哈希表 cntcnt 统计所有偶数元素出现的次数,然后找出出现次数最多且值最小的偶数元素。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是数组的长度。

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

出现最频繁的偶数元素题解:数组·哈希·扫描 | LeetCode #2404 简单