This problem is very tricky, especially when you need to solve it without extra spaces. I didn't think of any good idea, what a shame. I even didn't consider bits manipulation as a trial. Anyway, thanks to 1337c0d3r for his or her good explanation, this is really awesome.
public class Solution {
public int singleNumber(int[] A) {
// For this question, one point is very important:
//If you sum the ith bit of all numbers and mod 3,
//it must be either 0 or 1 due to the constraint of this problem
//where each number must appear either three times or once.
//This will be the ith bit of that "single number".
int ones = 0, twos = 0, threes = 0;
// ones as a bitmask to represent the ith bit had appeared once.
// twos as a bitmask to represent the ith bit had appeared twice.
// threes as a bitmask to represent the ith bit had appeared three times.
for(int i = 0; i < A.length; i ++){
twos |= ones & A[i];// if the ith bit of ones and A[i] are both 1, it means this bit can appear twice
ones ^= A[i];// XOR with A[i], clear the bits with same value as A[i], only keep bits with different //values,
// since if one bit appear once, and current element does not contain this bit,
// then this bit still appear once, similar to other cases
threes = ones & twos;// only if one bit appears once and twice, then this bit can appear 3rd times
ones &= ~threes;//clear the ith bit of both ones and twos to 0
twos &= ~threes;
}
return ones;
}
}
No comments:
Post a Comment