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遇到就写写代码吧
思路:将所有的数都异或起来,最后得到x和y的异或和sum(设要求的两数为x、y)。由于相同为0相异为1,则遍历sum二进制找到一个不为0的位置,将所有数组中该处为0的数、该处为1的数分别与sum异或起来可得到答案。时间O(32n),空间O(1)
顺便,学了种求最后一位是1的新写法,觉得很赞呀~~~
lastBit = (n & (n - 1)) ^ n;神奇的位运算,神奇,神奇 class Solution { public: vector<int> singleNumber(vector<int>& nums) { int sum = 0; for (int i = 0; i < nums.size(); ++i) { sum ^= nums[i]; } vector<int> ans; int sum2 = sum; for (int i = 0; i < 32; ++i) { if (((sum >> i) & 1) == 0) continue; for (int j = 0; j < nums.size(); ++j) { if ((nums[j] >> i) & 1) sum ^= nums[j]; else sum2 ^= nums[j]; } break; } ans.push_back(sum); ans.push_back(sum2); return ans; } };