LeetCode 题解工作台
在长度 2N 的数组中找出重复 N 次的元素
给你一个整数数组 nums ,该数组具有以下属性: nums.length == 2 * n . nums 包含 n + 1 个 不同的 元素,其中 n 个值在数组中出现 恰好一次 。 nums 中恰有一个元素重复 n 次 找出并返回重复了 n 次的那个元素。 示例 1: 输入: nums = [1…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
由于数组 一共有 个元素,其中有 $n + 1$ 个不同的元素,且有一个元素重复了 次,说明数组中的其余 个元素都是不同的。 因此,我们只需要遍历数组 ,用哈希表 记录遍历过的元素。当遍历到某个元素 时,如果 在哈希表 中已经存在,说明 是重复的元素,直接返回 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums ,该数组具有以下属性:
nums.length == 2 * n.nums包含n + 1个 不同的 元素,其中n个值在数组中出现 恰好一次。nums中恰有一个元素重复n次
找出并返回重复了 n 次的那个元素。
示例 1:
输入:nums = [1,2,3,3] 输出:3
示例 2:
输入:nums = [2,1,2,5,3,2] 输出:2
示例 3:
输入:nums = [5,1,5,2,5,3,5,4] 输出:5
提示:
2 <= n <= 5000nums.length == 2 * n0 <= nums[i] <= 104nums由n + 1个 不同的 元素组成,且其中一个元素恰好重复n次
解题思路
方法一:哈希表
由于数组 一共有 个元素,其中有 个不同的元素,且有一个元素重复了 次,说明数组中的其余 个元素都是不同的。
因此,我们只需要遍历数组 ,用哈希表 记录遍历过的元素。当遍历到某个元素 时,如果 在哈希表 中已经存在,说明 是重复的元素,直接返回 即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
s = set()
for x in nums:
if x in s:
return x
s.add(x)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate explain the space-time trade-off in hash-based solutions?
- question_mark
Does the candidate consider stopping the scan early upon identifying the repeated element?
- question_mark
Is the candidate aware of the space complexity and its optimization?
常见陷阱
外企场景- error
Using unnecessary space by tracking all elements instead of just the repeated one.
- error
Failing to stop the array scan early once the repeated element is found.
- error
Misunderstanding the time complexity of hash lookups and scanning.
进阶变体
外企场景- arrow_right_alt
What if the array is sorted? How would the solution change?
- arrow_right_alt
Can we solve this problem without using a hash table? What other techniques can be applied?
- arrow_right_alt
What if there are multiple repeated elements with different frequencies?