一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2 <= nums.length <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
首先将数组排序,然后依次从前往后遍历,如果前后两个元素相等,则向后偏移两个位置,否则记录当前元素,向后偏移一个位置。该方法由于使用sort()的缘故,会使得算法的时间复杂度变为O(NlogN)
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
vector<int> res;
int n = nums.size();
int i = 0;
sort(nums.begin(), nums.end());
for (i = 0; i < n - 1;) {
if (nums[i] == nums[i + 1]) {
i += 2;
continue;
}
res.push_back(nums[i]);
i++;
}
if (i == n - 1) {
res.push_back(nums[i]);
}
return res;
}
};
采用官网上给出的方法:
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
vector<int> res;
int ans = 0;
int a = 0, b = 0;
for (auto &i: nums) {
ans ^= i;
}
int div = 1;
while ((div & ans) == 0) {
div <<= 1;
}
for (auto &i: nums) {
if (div & i) {
a ^= i;
}
else {
b ^= i;
}
}
res.push_back(a);
res.push_back(b);
return res;
}
};