[leetcode] 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?

https://oj.leetcode.com/problems/single-number-ii/

思路1:好理解的方法,用一个32长度的数组保存每一位为1的数目,然后最后%3之后剩下的数字就是结果。

思路2:思路1可以改进空间,只用ones,twos,threes三个变量即可。

public class Solution {
    public int singleNumber(int[] A) {
        int n = A.length;
        int[] count = new int[32];
        int result = 0;
        for (int i = 0; i < 32; i++) {
            for (int j = 0; j < n; j++) {
                if (((A[j] >> i) & 1) != 0) {
                    count[i]++;
                }
            }
            result |= ((count[i] % 3) << i);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] a = new int[] { 1, 1, 1, 2, 2, 2, 5, 5, 5, 6 };
        System.out.println(new Solution().singleNumber(a));
    }
}

第二遍记录:不需要数组,一个变量count就足够了,遍历循环每一位的1,然后mod3 加到结果上。

public class Solution {
    public int singleNumber(int[] A) {
        int n = A.length;

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

参考:

http://www.acmerblog.com/leetcode-single-number-ii-5394.html

http://www.cnblogs.com/daijinqiao/p/3352893.html

http://rockylearningcs.blogspot.com/2014/02/single-number-ii-in-leetcode-in-java.html

原文地址:https://www.cnblogs.com/jdflyfly/p/3828929.html