LeetCode 题解工作台

唯一元素的和

给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。 请你返回 nums 中唯一元素的 和 。 示例 1: 输入: nums = [1,2,3,2] 输出: 4 解释: 唯一元素为 [1,3] ,和为 4 。 示例 2: 输入: nums = [1,1,1,1,1] 输出: …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以用数组或哈希表 `cnt` 统计数组 `nums` 中每个数字出现的次数,然后遍历 `cnt`,对于出现次数为 1 的数字,将其加入答案。 遍历结束后,返回答案即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

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

解题思路

方法一:计数

我们可以用数组或哈希表 cnt 统计数组 nums 中每个数字出现的次数,然后遍历 cnt,对于出现次数为 1 的数字,将其加入答案。

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),空间复杂度 O(M)O(M)。其中 nnmm 分别是数组 nums 的长度和 nums 中的最大值。

1
2
3
4
5
class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return sum(x for x, v in cnt.items() if v == 1)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

唯一元素的和题解:数组·哈希·扫描 | LeetCode #1748 简单