【LeetCode136 137】只出现一次的数字 ⅠⅡ
136 只出现一次的数字 Ⅰ
要时间复杂度O(n),不开空间,一个遍历异或赋值
class Solution {
public:
int singleNumber(vector<int>& nums) {
int x = 0;
for(int i= 0; i < nums.size(); i++){
x ^= nums[i];
}
return x;
}
};
137 只出现一次的数字 Ⅱ
模拟题136的二进制异或,这个是用位运算实现记录三次置零的方法
one: 二进制每位出现的第一次(数换成二进制,分成每位出现的次数是一样)
two: 二进制每位出现的第二次
three: 二进制每位出现的第三次
案列:[2 2 3 2]
二进制 | 开始 | 2 | 2 | 3 | 2 |
---|---|---|---|---|---|
one | 0x0000 | 0x0010 | 0x0000 | 0x0001 | 0x0011 |
two | 0x0000 | 0x0000 | 0x0010 | 0x0000 | 0x0000 |
three | 0x0000 | 0x0000 | 0x0000 | 0x0010 | 0x0000 |
class Solution {
public:
int singleNumber(vector<int>& nums) {
int one = 0;
int two = 0;
int three = 0;
for(int i = 0; i < nums.size(); i++){
two |= one & nums[i];
one ^= nums[i];
three = one & two;
one &= ~three;
two &= ~three;
}
return one;
}
};