leetcode 260 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.

Example:

Input:  [1,2,1,3,2,5]
Output: [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?

给定一个数组,其中有两个数只出现了一次,其他的数都出现了两次,求出这两个数。

这道题在面试时遇到,当时只能想到用一次异或求出出现不同的数和借助set来找出该数。后来面试官提示,异或为1代表该位两个数不相同,这样就可以将两个数分开。当时一知半解,故特写博客一篇作为记录。

正如我们所知,一次异或操作得到的值为要求的两数的异或值。由于存在两不同的数,因此该异或值一定不为0,对于该异或值中不为1的那一位,说明可以将数组分成两部分,一部分为数组该位值为1的,另一部分该位值为0,代码如下:

    vector<int> singleNumber(vector<int>& nums) {
        if (nums.size() < 2)return vector<int>();
        else if (nums.size() == 2)return nums;
        int all = 0;
        for (auto num:nums)
            all ^= num;
        int flag = 0x01;
        while (true) {
            if (flag & all)break;
            flag <<= 1;
        }
        int res1 = 0, res2 = 0;
        for (auto num : nums) {
            if (num & flag)
                res1 ^= num;
            else res2 ^= num;
        }
        vector<int> result;
        result.push_back(res1);
        result.push_back(res2);
        return result;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值