[leetcode] Single Number II

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

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

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

 

思路1:好理解的方法,用一個32長度的數組保存每一位爲1的數目,而後最後%3以後剩下的數字就是結果。app

思路2:思路1能夠改進空間,只用ones,twos,threes三個變量便可。spa

 

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 加到結果上。code

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;
    }
}

 

 

參考:htm

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

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

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

相關文章
相關標籤/搜索