您的位置:首页 > 其它

The Solution to Leetcode 137 Single Number II

2017-04-06 09:58 507 查看
Question:

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

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路:将上一道题改动一下,i=i+2变成i=i+3就行了。同时要判断数组元素个数为1,2,3,的时候的情况。
Answer:

class Solution {
public:
int singleNumber(vector<int>& nums) {
int i=0;
if(nums.size()==1)
return nums[i];
if(nums.size()==2)
return NULL;
if(nums.size()==3)
return NULL;
sort(nums.begin(), nums.end());
for(i==0;i<nums.size();i=i+3)
{
if(nums[i]!=nums[i+1])
return nums[i];
}
}
};

run code results:



Your input

[1 1 0 1 9 8 0 8 9 0 9 8 4 7 5 7 5 7 5]



Your answer

4



Expected answer

4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: