Featured image of post 剑指 Offer 56 - I. 数组中数字出现的次数

剑指 Offer 56 - I. 数组中数字出现的次数

题目描述

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是 O(n),空间复杂度是 O(1)。

示例 1:

  • 输入:nums = [4,1,4,6]
  • 输出:[1,6] 或 [6,1]

示例 2:

  • 输入:nums = [1,2,10,4,1,4,3,3]
  • 输出:[2,10] 或 [10,2]

限制:

  • 2 <= nums.length <= 10000

解法一:位运算

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
func singleNumbers(nums []int) []int {
    xor, n := 0, len(nums)
    for i := 0; i < n; i++ {
        xor ^= nums[i]
    }
    count := 0
    for xor & (1 << count) == 0 {
        count++
    }
    a, b := 0, 0
    for i := 0; i < n; i++ {
        if nums[i] & (1<<count) == 0{
            a ^= nums[i]
        } else {
            b ^= nums[i]
        }
    }
    return []int{a, b}
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/07/01 22:37:45
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计