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


//java裏int始終佔4個字節,32位,咱們外層循環遍歷32次,而後內層循環記錄0-31位每一位出現的次數,
//內層循環結束後將結果取餘於3即爲當前位的值
//時間複雜度O(32 * n), 空間複雜度O(1)
// 比方說 
//1101
//1101
//1101
//0011
//0011
//0011
//1010   這個unique的   
//----
//4340  1的出現次數  
//1010  餘3的話 就是那個惟一的數!
public class Solution {
    public int singleNumber(int[] A) {
        int res=0;
		int bit;
		for(int j=0;j<32;j++){
			bit=0;
			for(int i=0;i<A.length;i++){
				if((A[i]>>j&1)==1){
					bit++;
				}
			}
			bit=bit%3;
			res+=(1<<j)*bit;
		}		
		return res; 
    }
}
相關文章
相關標籤/搜索