136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
一开始提交的时候居然compile error,一直显示control reaches end of non-void function [-Werror=return-type]。后来加了句return 0;之
后才通过的。如果返回值是除void外的类型,那就必须得保证一定会有一个相应类型的返回值。恍然大悟~
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
/**********************************提交部分**********************************/
class Solution
{
public:
int singleNumber(vector<int>& nums)
{
sort(nums.begin(),nums.end());
for(int i=0; i<nums.size(); i=i+2)
{
if(nums[i]!=nums[i+1])
return nums[i];
}
return 0;
}
};
/*****************************************************************************/
int main()
{
Solution S;
vector<int> a;
int n;
scanf("%d",&n);
int tmp;
for(int i=0; i<n; i++)
{
scanf("%d",&tmp);
a.push_back(tmp);
}
int ans=S.singleNumber(a);
printf("%d\n",ans);
return 0;
}