Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2] Output: 3
Example 2:
Input: [0,1,0,1,0,1,99] Output: 99
题意:数组中只有一个数出现了一次,其他数都出现了三次,找到这个只出现一次的数。
分析:类似题目之前也写过,例如:【剑指Offer】数组中只出现一次的数字。
下面给出讨论区里一个精简的代码。首先要知道在这类题目中对于每个二进制位的运算都是相同的,所以可以对任意一个二进制位进行运算;其次,对于某一特定二进制位,ones表示1出现的次数,twos表示1出现了两次。
就样例1[2,2,3,2]来讨论。
nums[0] | nums[1] | nums[2] | nums[3] | ones | twos |
---|---|---|---|---|---|
2(10) | 2(10) | 0 | |||
2(10) | 0 | 2(10) | |||
3(11) | 1(01) | 0 | |||
2(10) | 3(11) | 0 |
上面的流程中的括号表示整数对应的二进制表示。补充一下:&~twos 与 &~ones表示出现三次的二进制位置为0
因此最后twos=0,结果最终为ones。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ones=0,twos=0;
for(auto x: nums){
ones = (ones^x) & ~twos;
twos = (twos^x) & ~ones;
}
return ones;
}
};