LeetCode 题解工作台

只出现一次的数字 II

给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。 请你找出并返回那个只出现了一次的元素。 你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。 示例 1: 输入: nums = [2,2,3,2] 输出: 3 示例 2: 输入: nums = […

category

2

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·结合·位运算·操作

bolt

答案摘要

我们可以枚举每个二进制位 ,对于每个二进制位,我们统计所有数字在该二进制位上的和,如果该二进制位上的和能被 整除,那么只出现一次的数字在该二进制位上为 ,否则为 。 时间复杂度 $O(n \times \log M)$,空间复杂度 。其中 和 分别是数组的长度和数组中元素的范围。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。

你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。

 

示例 1:

输入:nums = [2,2,3,2]
输出:3

示例 2:

输入:nums = [0,1,0,1,0,1,99]
输出:99

 

提示:

  • 1 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
lightbulb

解题思路

方法一:位运算

我们可以枚举每个二进制位 ii,对于每个二进制位,我们统计所有数字在该二进制位上的和,如果该二进制位上的和能被 33 整除,那么只出现一次的数字在该二进制位上为 00,否则为 11

时间复杂度 O(n×logM)O(n \times \log M),空间复杂度 O(1)O(1)。其中 nnMM 分别是数组的长度和数组中元素的范围。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ans = 0
        for i in range(32):
            cnt = sum(num >> i & 1 for num in nums)
            if cnt % 3:
                if i == 31:
                    ans -= 1 << i
                else:
                    ans |= 1 << i
        return ans
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for an efficient solution using bit manipulation techniques to handle large arrays within time and space constraints.

  • question_mark

    Candidates should avoid using hashmaps or arrays, focusing instead on bitwise operations to solve the problem.

  • question_mark

    Pay attention to how well the candidate handles the edge cases and optimizes the solution for constant space usage.

warning

常见陷阱

外企场景
  • error

    Relying on hashmaps or arrays, which violate the constant space requirement.

  • error

    Not correctly handling the bitwise operations, leading to incorrect results when tracking occurrences of the bits.

  • error

    Failing to consider edge cases such as when the array has only one element or all elements are negative.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implementing the solution using a different set of bitwise operations or bit tracking techniques.

  • arrow_right_alt

    Using different approaches like mathematical formulas or recursion instead of bit manipulation.

  • arrow_right_alt

    Handling arrays of varying sizes and input constraints, ensuring the solution works under all edge cases.

help

常见问题

外企场景

只出现一次的数字 II题解:数组·结合·位运算·操作 | LeetCode #137 中等