Title
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?
Solution
3种方式
排序 & 遍历
刚开始,用了一种笨方法。
直接排序,然后遍历,两个两个的进行比较,如果相同,继续比较;如果不同,说明这里有那个唯一的元素。
class Solution {
public:
int singleNumber(vector<int>& nums) {
if (nums.size() == 1) {
return nums[0];
}
sort(nums.begin(), nums.end());
decltype(nums.size()) i=0; //设为全局变量
for (i=1; i != nums.size(); ++i) { //i从1开始
if (nums[i-1] == nums[i]) {
++i;
}
else { //不同时,返回前一个
return nums[i-1];
}
}
return nums[i-1]; //处理最后一个元素
}
};
rungtime: 46ms
异或
class Solution {
public:
int singleNumber(vector<int>& nums) {
int last = 0;
// i^i==0; i^i^j==j;
for (const auto &i : nums) { //这里加&,从23ms->16ms
last ^= i;
}
return last;
}
};
runtime: 16ms
考虑map
class Solution {
public:
int singleNumber(vector<int>& nums) {
if (nums.size() == 1) {
return nums[0];
}
map<int, int> mNum;
for (const auto &key : nums) {
++mNum[key];
}
for (auto i = mNum.begin(); i != mNum.end(); ++i) {
if (i->second == 1) {
return i->first;
}
}
return -1;
}
};
runtime: 56ms