题目:
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?
题目:找到一组全都出现2次的数据中唯一一个只出现过一次的数据。
思路:因为要求时间了复杂度是线性了,思路是先排个序,然后遍历一次找到出现次数为1的。复杂度是O(nlogn+n)
#include<stdio.h>
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
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];
}
}
}
int main()
{
int a[5] = { 3, 3, 2, 4, 4 };
vector<int> nums(a, a + 5);
int result;
result = singleNumber(nums);
cout << result << endl;
return 0;
}