LeetCode #260 Single Number III

来源:互联网 发布:收获日2捡弹率算法 编辑:程序博客网 时间:2024/05/03 21:12

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:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
136题 single number的晋级版。136只有一个single number,思路是将所有的数做异或,剩下的就是那个single number。
在这里也先采用异或的方式,这两个single numbers分别为a和b,则得到的结果xorx=a^b是关于ab的复合信息。
这里有一句useful code:n=xorx&(~(xorx-1)); 得到的n是xorx末位起第一个不为0的位数。也就是a和b末位起第一个不同的位数。我们可以把这个n当成一个flag,将数组分成两部分。该位不为1的(x&n!=0)为一组,其余为一组。将xorx分别与每组数做异或,就得到了a和b。
class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        int len = nums.size();        int xorx = 0;        for(int i=0;i<len;i++){            xorx=xorx^nums[i];        }        int one = xorx & (~(xorx-1));        vector<int> result(2,0);        for(int j=0;j<len;j++){            if((nums[j]&one)!=0)            result[0]=nums[j]^result[0];            else            result[1]=nums[j]^result[1];        }                return result;    }};


0 0
原创粉丝点击