给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。
样例
给出 [1,2,2,3,4,4,5,3],返回 1和5
挑战
O(n)时间复杂度,O(1)的额外空间复杂度
Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.
Example
Given [1,1,2,3,3,3,2,2,4,1] return 4
Challenge
One-pass, constant extra space.
思路:所有数字每一位之和模3
public class Solution {
/**
* @param A : An integer array
* @return : An integer
*/
public int singleNumberII(int[] A) {
int[] B = new int[32];
for(int j = 0; j < A.length; j++){
for(int i = 0; i < 32; i++) {
if((1<<i & A[j]) == 1<<i) {
B[i] = (B[i] + 1) % 3;
}
}
}
int result = 0;
for(int i = 0; i < 32; i++) {
result = 2 * result + B[31-i];
}
return result;
}
}