260. Single Number III

来源:互联网 发布:比较好的淘宝培训机构 编辑:程序博客网 时间:2024/03/28 23:44

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.

  1. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
这个应该是剑指offer的一道题,具体思路如下:
先对所有数字异或一遍,再用mask=t&(~(t-1));求出最右边的一个1的位置。
再以那个位置是否为1,将所有的数字划分为2组,a和b一定分别在其中的一组。
这个时候就可以直接异或分别得到那两个数字了。

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


0 0
原创粉丝点击