Single Number II

Tags: Bit Manipulation, Medium

Question

Problem Statement

Given an array of integers, every element appears three times except for
one, which appears exactly once. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it
without using extra memory?

Challenge

One-pass, constant extra space.

题解1 - 逐位处理

上题 Single Number 用到了二进制中异或的运算特性,这题给出的元素数目为3*n + 1,因此我们很自然地想到如果有种运算能满足「三三运算」为0该有多好!对于三个相同的数来说,其相加的和必然是3的倍数,仅仅使用这一个特性还不足以将单数找出来,我们再来挖掘隐含的信息。以3为例,若使用不进位加法,三个3相加的结果为:

  1. 0011
  2. 0011
  3. 0011
  4. ----
  5. 0033

注意到其中的奥义了么?三个相同的数相加,不仅其和能被3整除,其二进制位上的每一位也能被3整除!因此我们只需要一个和int类型相同大小的数组记录每一位累加的结果即可。时间复杂度约为 O((3n+1)\cdot sizeof(int) \cdot 8)

Python

  1. class Solution(object):
  2. def singleNumber(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: int
  6. """
  7. if nums is None:
  8. return 0
  9. result = 0
  10. for i in xrange(32):
  11. bit_i_sum = 0
  12. for num in nums:
  13. bit_i_sum += ((num >> i) & 1)
  14. result |= ((bit_i_sum % 3) << i)
  15. return self.twos_comp(result, 32)
  16. def twos_comp(self, val, bits):
  17. """
  18. compute the 2's compliment of int value val
  19. e.g. -4 ==> 11100 == -(10000) + 01100
  20. """
  21. return -(val & (1 << (bits - 1))) | (val & ((1 << (bits - 1)) - 1))

C++

  1. class Solution {
  2. public:
  3. /**
  4. * @param A : An integer array
  5. * @return : An integer
  6. */
  7. int singleNumberII(vector<int> &A) {
  8. if (A.empty()) {
  9. return 0;
  10. }
  11. int result = 0, bit_i_sum = 0;
  12. for (int i = 0; i != 8 * sizeof(int); ++i) {
  13. bit_i_sum = 0;
  14. for (int j = 0; j != A.size(); ++j) {
  15. // get the *i*th bit of A
  16. bit_i_sum += ((A[j] >> i) & 1);
  17. }
  18. // set the *i*th bit of result
  19. result |= ((bit_i_sum % 3) << i);
  20. }
  21. return result;
  22. }
  23. };

Java

  1. public class Solution {
  2. public int singleNumber(int[] nums) {
  3. int single = 0;
  4. final int INT_BITS = 32;
  5. for (int i = 0; i < INT_BITS; i++) {
  6. int bitSum = 0;
  7. for (int num : nums) {
  8. bitSum += ((num >>> i) & 1);
  9. }
  10. single |= ((bitSum % 3)<< i);
  11. }
  12. return single;
  13. }
  14. }

源码解析

  1. 异常处理
  2. 循环处理返回结果resultint类型的每一位,要么自增1,要么保持原值。注意i最大可取 $$8 \cdot sizeof(int) - 1$$, 字节数=>位数的转换
  3. 对第i位处理完的结果模3后更新result的第i位,由于result初始化为0,故使用或操作即可完成

Python 中的整数表示理论上可以是无限的(求出处),所以移位计算得到最终结果时需要转化为2的补码。此方法参考自 Two’s Complement in Python

Reference

Single Number II - Leetcode Discuss 中抛出了这么一道扩展题:

  1. Given an array of integers, every element appears k times except for one. Find that single one which appears l times.

@ranmocy 给出了如下经典解:

We need a array x[i] with size k for saving the bits appears i times. For every input number a, generate the new counter by x[j] = (x[j-1] & a) | (x[j] & ~a). Except x[0] = (x[k] & a) | (x[0] & ~a).

In the equation, the first part indicates the the carries from previous one. The second part indicates the bits not carried to next one.

Then the algorithms run in O(kn) and the extra space O(k).

Java

  1. public class Solution {
  2. public int singleNumber(int[] A, int k, int l) {
  3. if (A == null) return 0;
  4. int t;
  5. int[] x = new int[k];
  6. x[0] = ~0;
  7. for (int i = 0; i < A.length; i++) {
  8. t = x[k-1];
  9. for (int j = k-1; j > 0; j--) {
  10. x[j] = (x[j-1] & A[i]) | (x[j] & ~A[i]);
  11. }
  12. x[0] = (t & A[i]) | (x[0] & ~A[i]);
  13. }
  14. return x[l];
  15. }
  16. }