題目描述:
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?
思考:
需要線性的時間,也就是遍歷一次把和n有關,空間是常數。學習了網上的方法,int四個字節,一共32位,依次保存從1到32的位置上這個數組中二進制表示在當前位置出現1的次數,再遍歷32個位置上的次數,分別和3求餘,如果出現餘數爲1,說明這個1就是我們要找的那個數的二進制表示相對位置的1,然後使用左移位配合或運算組裝我們要的那個數。
代碼:
public int singleNumber(int[] nums) {
int[] bitCountForOne = new int[32];
int res = 0;
for(int i = 0 ; i < 32 ; i++){
for( int ii = 0 ; ii < nums.length ; ii++){
bitCountForOne[i] += (nums[ii]>>i & 1);
}
res |= (bitCountForOne[i]%3)<<i;
}
return res;
}