#137 Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解法:先对数组进行排序, 然后进行统计出现的个数,如果等于3,则进行循环,否则就跳出循环了
class Solution {
public:
int singleNumber(vector<int>& nums) {
int len = nums.size();
sort(nums.begin(), nums.end());
int start = nums[0] ;
int count = 1;
for(int i = 1; i < len; i++) {
if(start == nums[i]) {
count++;
}
else {
if(count != 3) return start;
else {
start = nums[i];
count = 1;
}
}
}
return start;
}
};

浙公网安备 33010602011771号