Problems:
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:
把这道题分为Medium难度我就有点尴尬了= - =
要求满足线性空间复杂度,用运算符解。
首先,在原始数组中,只有有两个数只出现一次,其余数字均出现两次。我们对整个数组数字进行异或,最终得到的结果即等同于所求两数的异或值。
因为两数不相同,所以至少在某一位上异或值为1,那么接下来,就要找出第一个为1的位数是第几位。用变量bit表示运算结果。
最后遍历数组,对每个数和之前算出bit进行与运算,找出那两个数。
Code(C++):
1 class Solution { 2 public: 3 vector<int> singleNumber(vector<int>& nums) { 4 int n = nums[0]; 5 6 int x = 0; 7 for(int n: nums) 8 x^=n; //获取两数的异或值 9 int bit; 10 int num1 = 0,num2 = 0; 11 bit = x & ~(x-1); //获取两数最低位不相同值的位数 12 for(int n: nums) 13 { 14 if(n & bit) 15 num1^=n; 16 else 17 num2^=n; 18 } 19 return vector<int> {num1, num2}; 20 } 21 };