[LeetCode]260. Single Number III

来源:互联网 发布:英镑 知乎 编辑:程序博客网 时间:2024/05/22 08: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?\
思路:

扫两遍,第一遍全异或得值temp。取temp中最低位不为0的位,其余位置0。如temp = 6 = 0x110,则取0x010。

扫第二遍,所有 i & 0x010 == 0x010的数异或得一个结果,其余数异或得另一个结果。

原理是两个不同的数至少会有一个bit位不同,造成全异或的结果中至少一位为1.那么以该位做区分,即可得两数。

vector<int> singleNumber(vector<int>& nums) {        vector<int> result;              int len=nums.size();        int temp=0,m=0,n=0;        for(int i=0;i<len;i++)        <span style="white-space:pre"></span>temp=temp^nums[i];        int dif=1;        while((dif&temp)!=dif)        <span style="white-space:pre"></span>dif=dif<<1;        for(int j=0;j<len;j++)        {        <span style="white-space:pre"></span>if((nums[j]&dif)==dif)        <span style="white-space:pre"></span>m=nums[j]^m;        <span style="white-space:pre"></span>else        <span style="white-space:pre"></span>n=nums[j]^n;        }        result.push_back(m);<span style="white-space:pre"></span>    result.push_back(n);        return result ;    }



0 0
原创粉丝点击