260. Single Number III

来源:互联网 发布:网络机顶盒怎么安装 编辑:程序博客网 时间:2024/04/25 13:15

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?

1.我的答案 

当然是最直接的啦,用一个哈希表存储,最后来遍历一遍

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        map<int,int> mp;        vector<int> res;        int len = nums.size();        for(int i = 0; i < len; i++){            if(mp.find(nums[i]) == mp.end()){                mp[nums[i]] = 1;            }            else                mp[nums[i]]++;        }        for(auto iter = mp.begin(); iter != mp.end(); iter++){            if(iter->second == 1)            res.push_back(iter->first);        }        return res;    }};

2.看了别人答案做的

思路:先把所有的值都异或一遍,相同的值异或异或肯定是0,则剩下的值就是单个出现的这两个数的异或结果。此时找该数的最右边(最左边也一样)第一次出现的1 的位置(该位置对应的那两个数一定是0和1),用此位置将该数组分为两部分。一部分是此位置为1的数,另一部分是此位置为0的数。同时这两边数各自含有一个唯一出现一次的数,其余都是出现两次的数。然后找出这个只出现一次的数即可。

这里有个小技巧:

要得到最右边第一次出现1的位置为1的数,可用以下方法:

int bit = a & ~(a-1);

bit即可得到a中右边第一次出现1的数。

例如: a = 110, 则bit = 110 & 010 = 010

以下是代码部分:

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        int temp = 0;        for(int i = 0; i < nums.size(); i++){            temp ^= nums[i];        }        int xors = temp & ~(temp - 1);        int num1 = 0, num2 = 0;        for(int j = 0; j < nums.size(); j++){            if((nums[j] & xors) > 0)                num1 ^= nums[j];            else                num2 ^= nums[j];        }        vector<int> res;        res.push_back(num1);        res.push_back(num2);        return res;    }};


0 0
原创粉丝点击