Question
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?
本题难度Medium。(我觉得已经可以算Hard了)
位运算
【复杂度】
时间 O(N) 空间 O(1)
【思路】
用one
记录到当前处理的元素为止,二进制1出现“1次”(mod3之后的1)有哪些二进制位;用two
记录到当前处理的元素为止,二进制1出现“2次”(mod3之后的2)有哪些二进制位。one
和two
中同时为1的二进制位表示该位上1出现了3次,此时需要清零。实际上就是在二进制位上进行mod3的运算。
【代码】
public class Solution {
public int singleNumber(int[] nums) {
//require
int one=0,two=0,three=0;
//invariant
for(int i:nums){
two|=(one&i);
one^=i;
three=~(one&two);
one&=three;
two&=three;
}
//ensure
return one;
}
}