您的位置:首页 > 其它

260. Single Number III

2016-09-04 10:32 190 查看

Title

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

The order of the result is not important. So in the above example, [5, 3] is also correct.

Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

Solution

map

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
map<int, int> mNum;

for (const auto &key : nums) {
++mNum[key];
}

vector<int> num;

for (auto i = mNum.begin(); i != mNum.end(); ++i) {
if (i->second == 1) {
num.push_back(i->first); //不可用下标运算符去给vector添加元素!int j=0; num[j]=1; X
}
}

return num;
}
};


runtime: 36ms

排序 & 遍历

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
if (nums.size() == 2) {
return nums;
}

sort(nums.begin(), nums.end());

decltype(nums.size()) i = 1;
vector<int> num;

while (i != nums.size()) {
if (nums[i-1] == nums[i]) { //vector数组名字易混,注意!
i += 2;
}
else {
num.push_back(nums[i-1]);
++i;
}

if (num.size() == 2) {
return num;
}
}

if (i == nums.size()) { //处理这种情况:1,1,2,2,3,5
num.push_back(nums[i-1]);
}

return num;
}
};


runtime: 32ms

位运算

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