leetcode-260. Single Number III

来源:互联网 发布:淘宝网手套 编辑:程序博客网 时间:2024/05/01 04:39

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?

思路:遍历一遍得到一个数,取其中一个bit为1的位置,根据此bit位值将数组分成两组,分别遍历异或,最后求得的值就是两个唯一的值

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        //遍历异或        int length = nums.size();        if(length == 0)        {            vector<int> temp(2,0);            return temp;        }        if(length == 1)        {            vector<int> temp(2,0);            temp[0] = nums[0];            return temp;        }        int result1 = nums[0];        for(int i = 1;i < length;i++)        {            result1 = result1^nums[i];        }        int bitOneFoot = 0;        while((result1 & 0x01) == 0 && result1 != 0)        {            bitOneFoot++;            result1 = result1>>1;        }        bitOneFoot = pow(2,bitOneFoot);        //按bit位把数组分成两组        result1 = 0;        int result2 = 0;        for(int i=0;i < length;i++)        {            if(nums[i] & bitOneFoot)            {                result1 ^= nums[i];            }            else            {                result2 ^= nums[i];            }        }        vector<int> result;        if(result1 < result2)        {            result.push_back(result1);            result.push_back(result2);        }        else        {            result.push_back(result2);            result.push_back(result1);        }        return result;    }};
0 0
原创粉丝点击