题目:
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?
思路:
我们在Leetcode中遇到一个类似的题目,就是说数组中只有一个数只出现过一次,其他的都出现了两次。这道题目的思路和那题一样,只是比上一道题目多了一个步骤:首先将所有数都一起异或,得到的结果就是这两个只出现一次的数的异或。然后再检查这个结果的哪一位为1,则说明只出现一次的两个数在这一位肯定不相等。然后就可以根据与这个数相与是否为0来将数组分为两半,则这两个只出现一次的数会分别处在两个不同的数组中。此时问题就回到了原来题目的思路,只要让子数组内部元素全部异或一下,得到的两个数就是最终要的只出现一次的数。
代码:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int tem = 0;
for (auto val : nums) {
tem ^= val;
}
int lowBit = tem & (-tem);
vector<int> vec1, vec2;
for (auto val : nums) {
if (val & lowBit) {
vec1.push_back(val);
}
else {
vec2.push_back(val);
}
}
int num1 = 0, num2 = 0;
for (auto val : vec1) {
num1 = num1 ^ val;
}
for (auto val : vec2) {
num2 = num2 ^ val;
}
return vector<int>{num1, num2};
}
};
本文介绍了一种线性时间复杂度的算法,用于从数组中找出仅出现一次的两个元素。通过异或运算找到这两个元素,并详细解释了实现过程。
8万+

被折叠的 条评论
为什么被折叠?



