Single-Number-II

题目地址

LeetCode#137 Single Number II

题目描述

  Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

解题思路

  将数组排序,之后遍历查找就可以了。直接看代码

解题代码【.CPP】

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());
bool isDup = false;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] != nums[i-1]){
if (!isDup) return nums[i-1];
isDup = false;
} else {
isDup = true;
}
}
return nums[nums.size()-1];
}
};
0%