[Leetcode] Single Number III

来源:互联网 发布:js里的值给input 编辑:程序博客网 时间:2024/06/16 10:19
问题描述: 

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?

分析:做了single1,single2再来做这道题发现还是不会,将vector中的元素做异或之后,得到的是两个不同元素的异或值,即两个元素的信息混合在一起。 

如何将二者分开,想了好久没想到办法。网友的介绍是利用两个元素的异或值(说明,要找的元素的对应位不同),利用这个特点将原有的序列分为两部分,这样,元素A和元素B分别在两个不同的序列里面了。 

这里面还有一个很巧妙的地方是,使用n&(~(n-1))可以取出元素的最后一个1的位置。

代码(C++):

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        vector<int> ans(2,0);        int aorb=0;        for(int i=0;i<nums.size();i++)            aorb^=nums[i];        int ma=aorb&(~(aorb-1));        for(int i=0;i<nums.size();i++){            if(ma&nums[i])                ans[0]^=nums[i];            else                ans[1]^=nums[i];        }        return ans;    }};

转:http://www.lai18.com/content/1577393.html


0 0