【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;
}
};