Leetcode 137. Single Number II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Single Number II

2. Solution

  • Simple Method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int i = 0;
while(i < nums.size() - 1) {
if(nums[i] == nums[i + 1]) {
i += 3;
}
else {
return nums[i];
}
}
return nums[nums.size() - 1];
}
};
  • O(N)
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a = 0;
int b = 0;
for(int i = 0; i < nums.size(); i++) {
a = (a ^ nums[i]) & (~b);
b = (b ^ nums[i]) & (~a);
}
return a;
}
};

Reference

  1. https://leetcode.com/problems/single-number-ii/description/

  2. https://leetcode.com/problems/single-number-ii/discuss/43294/Challenge-me-thx

如果有收获,可以请我喝杯咖啡!