260. Single Number III

来源:互联网 发布:约翰施特劳斯乐团 知乎 编辑:程序博客网 时间:2024/06/06 08:27

题目

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?


思路

遍历全部异或,求出两个唯一值的异或结果,结果肯定非0,已其中bit为1的位数将入参分为两组。
再做一次遍历异或,求出结果。


代码

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        vector<int> resultArry;        if(nums.size() < 2)        {            return resultArry;        }        //算出两个唯一数的异或结果,并求出两者不同bit的最低位index        int xorNum = 0;        int bitIndex = 0;        for(size_t i = 0;i < nums.size();i++)        {            xorNum ^= nums[i];        }        while(!(xorNum & 0x01))        {            bitIndex++;            xorNum >>= 1;        }        //根据最低bit不同将入参分成两组        int num1Rslt = 0;        int num2Rslt = 0;        for(size_t i = 0;i < nums.size();i++)        {            if((nums[i] >> bitIndex)& 0x01)            {                num1Rslt ^= nums[i];            }            else            {                num2Rslt ^= nums[i];            }        }        resultArry.push_back(num1Rslt);        resultArry.push_back(num2Rslt);        return resultArry;    }};
0 0
原创粉丝点击