您的位置:首页 > 其它

LeetCode题解–260. Single Number III

2017-06-15 14:45 387 查看

链接

LeetCode题目:https://leetcode.com/problems/single-number-iii/

难度:Medium

题目

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.

题目大意是给定一个数组,其中只有2个元素各出现1次,其他元素都出现了2次,找出那2个元素(元素的位置可以不同)。

分析

一开始想到的是用一个unordered_set维护这个数组,遇到新的元素加入set,遇到重复的元素则删除。时间和空间复杂度都是O(N)。

其实还有不借助set的解法。根据异或的性质(a^a=0, a^0=a),如果我们把数组的数字全部异或一遍,得到的值flag就是那两个元素a和b异或的结果。如果a和b不等,意味着它们至少在某一位上不同,这一位可以从flag中得到。然后根据这一位把数组分为两部分,一部分在这一位上为0,另一部分在这一位上为1,分别将这两部分的全部元素异或,最后得到的值就是a和b。

代码

class Solution {
public:
vector<int> singleNumber(vector<int> &nums) {
int flag = 0;
for (auto num:nums) {
flag ^= num;
}
int mask = 1;
while (!(flag & mask)) {
mask = mask << 1;
}
int a = 0, b = 0;
for (auto num:nums) {
if (num & mask) a ^= num;
else b ^= num;
}
vector<int> ans = {a, b};
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: