Single Number II

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

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

创建一个长度为32的数组a,a[i]表示所有数字在i位出现的次数。
假如a[i]是3的整数倍,则忽略;否则就把该位取出来组成答案。
空间复杂度O(1).

int sol1(int A[], int n)
{
    int count[32];
    int result = 0;
    for (int i = 0;i < 32;++i) {
        count[i] = 0;
        for (int j = 0;j < n;++j) {
            if ((A[j] >> i) & 1) count[i] = (count[i] + 1) % 3;
        }
        result |= (count[i] << i);
    }
    return result;
}

另一个方法,同样的原理,用3个整数来表示INT的各位的出现次数情况,one表示出现
了1次,two表示出现了2次。当出现3次的时候该位清零。最后答案就是one的值。

int sol2(int A[], int n)
{
    int one = 0, two = 0, three = 0;
    for (int i = 0;i < n;++i) {
        two |= one & A[i];
        one ^= A[i];
        three = one & two;
        one &= ~three;
        two &= ~three;
    }
    return one;
}

 

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         int count[] = new int[32];
 5         int result = 0;
 6         for (int i = 0; i < 32; i ++){
 7             for (int j = 0; j < A.length; j ++) {
 8                 if (((A[j] >> i) & 1) == 1) 
 9                     count[i] = (count[i] + 1) % 3;
10             }
11             result |= (count[i] << i);
12         }
13         return result;
14     }
15 }

 

posted on 2013-10-11 11:17  Step-BY-Step  阅读(279)  评论(0编辑  收藏  举报

导航