Given
Have you met this question in a real interview? 3*n + 1
numbers, every numbers occurs triple times except one, find it.
Yes
Example
Given
[1,1,2,3,3,3,2,2,4,1]
return 4
Challenge
public class Solution {
One-pass, constant extra space.
/**
* @param A : An integer array
* @return : An integer
*/
public int singleNumberII(int[] A) {
// write your code here
int[] count = new int[32];
for(int i = 0; i < 32; i++){
for(int j = 0; j < A.length; j++){
count[i] += (A[j] >> i & 1);
}
}
int res = 0;
for(int i = 0; i < 32; i++){
res += (count[i] % 3) << i;
}
return res;
}
}
Here is another solution
ReplyDeletepublic class Solution {
public int singleNumber(int[] nums) {
int p = 0;
int q = 0;
for(int i = 0; i<nums.length; i++){
p = q & (p ^ nums[i]);
q = p | (q ^ nums[i]);
}
return q;
}
}
Analysis from this blog post : http://traceformula.blogspot.com/2015/08/single-number-ii-how-to-come-up-with.html