[leetcode]Single Number III

来源:互联网 发布:ai软件卡通图片 编辑:程序博客网 时间:2024/06/11 04:45

Single Number III

题目:

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?

思路:

    一开始想到的是类似于SingleNumber I的解法,可以求出两数异或的数值,于是考虑是否能用其他方式求出两数的其他关系(小学二元一次方程思维无奈)。    由两数异或的值可以得知这两个数在哪个数位是不同的(这里用a&-a相当于得出a中最低位的1),然后根据这一特征,将数组里所有数分为两部分,然后再对两个子数组用SingleNumber I的解法即可。
class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        int a=0;        vector<int> result{0,0};        for(auto i=nums.begin();i!=nums.end();++i)            a^=*i;        int b=a&-a;        for(auto i=nums.begin();i!=nums.end();++i)        {            if((*i&b)==b)                result[0]^=*i;            else                result[1]^=*i;        }        return result;    }};
0 0
原创粉丝点击