LeetCode 题解工作台
检查元素频次是否为质数
给你一个整数数组 nums 。 如果数组中任一元素的 频次 是 质数 ,返回 true ;否则,返回 false 。 元素 x 的 频次 是它在数组中出现的次数。 质数是一个大于 1 的自然数,并且只有两个因数:1 和它本身。 示例 1: 输入: nums = [1,2,3,4,5,4] 输出: t…
5
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 统计每个元素的频次。然后遍历 中的值,判断是否有质数,如果有则返回 `true`,否则返回 `false`。 时间复杂度 $O(n \times \sqrt{M})$,空间复杂度 。其中 是数组 的长度,而 是 中的最大值。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums。
如果数组中任一元素的 频次 是 质数,返回 true;否则,返回 false。
元素 x 的 频次 是它在数组中出现的次数。
质数是一个大于 1 的自然数,并且只有两个因数:1 和它本身。
示例 1:
输入: nums = [1,2,3,4,5,4]
输出: true
解释:
数字 4 的频次是 2,而 2 是质数。
示例 2:
输入: nums = [1,2,3,4,5]
输出: false
解释:
所有元素的频次都是 1。
示例 3:
输入: nums = [2,2,2,4,4]
输出: true
解释:
数字 2 和 4 的频次都是质数。
提示:
1 <= nums.length <= 1000 <= nums[i] <= 100
解题思路
方法一:计数 + 判断质数
我们用一个哈希表 统计每个元素的频次。然后遍历 中的值,判断是否有质数,如果有则返回 true,否则返回 false。
时间复杂度 ,空间复杂度 。其中 是数组 的长度,而 是 中的最大值。
class Solution:
def checkPrimeFrequency(self, nums: List[int]) -> bool:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
cnt = Counter(nums)
return any(is_prime(x) for x in cnt.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate identifies the prime checking pattern and efficiently counts frequencies.
- question_mark
Candidate demonstrates knowledge of basic number theory to optimize the primality check.
- question_mark
Candidate implements a clear and correct array scanning strategy with hash table lookups.
常见陷阱
外企场景- error
Not implementing an efficient prime checking function leading to slower performance.
- error
Incorrectly counting frequencies or misunderstanding the concept of frequency.
- error
Failing to handle edge cases such as small arrays or the case where no element has a prime frequency.
进阶变体
外企场景- arrow_right_alt
What if the array contains repeated zeros?
- arrow_right_alt
What if the array has a length of 1?
- arrow_right_alt
How does the solution change if the array contains a larger range of numbers?