LeetCode 题解工作台
唯一元素的和
给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。 请你返回 nums 中唯一元素的 和 。 示例 1: 输入: nums = [1,2,3,2] 输出: 4 解释: 唯一元素为 [1,3] ,和为 4 。 示例 2: 输入: nums = [1,1,1,1,1] 输出: …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用数组或哈希表 `cnt` 统计数组 `nums` 中每个数字出现的次数,然后遍历 `cnt`,对于出现次数为 1 的数字,将其加入答案。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。
请你返回 nums 中唯一元素的 和 。
示例 1:
输入:nums = [1,2,3,2] 输出:4 解释:唯一元素为 [1,3] ,和为 4 。
示例 2:
输入:nums = [1,1,1,1,1] 输出:0 解释:没有唯一元素,和为 0 。
示例 3 :
输入:nums = [1,2,3,4,5] 输出:15 解释:唯一元素为 [1,2,3,4,5] ,和为 15 。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 100
解题思路
方法一:计数
我们可以用数组或哈希表 cnt 统计数组 nums 中每个数字出现的次数,然后遍历 cnt,对于出现次数为 1 的数字,将其加入答案。
遍历结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 nums 的长度和 nums 中的最大值。
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
cnt = Counter(nums)
return sum(x for x, v in cnt.items() if v == 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should clearly explain the hash table usage and the need for frequency counting.
- question_mark
Look for knowledge of iterating over a hash map to filter out elements with frequency greater than 1.
- question_mark
Assess if the candidate considers early termination or optimizing the solution.
常见陷阱
外企场景- error
Forgetting to handle edge cases like arrays with no unique elements or arrays with all elements the same.
- error
Misunderstanding the concept of unique elements, leading to incorrect frequency counting.
- error
Inefficient solutions that repeatedly scan the array, instead of using a hash table for counting.
进阶变体
外企场景- arrow_right_alt
What if negative numbers are allowed in the array?
- arrow_right_alt
How would the solution change if the array was sorted?
- arrow_right_alt
Can the problem be solved with constant space?