260. Single Number III(C++)

题目:

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?

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {

    }
};

翻译:

给定一个数字nums的数组,其中恰好两个元素只出现一次,所有其他元素出现正好两次。 找到只出现一次的两个元素。

例如:

给定nums = [1,2,1,3,2,5],return [3,5]。

注意:
结果的顺序并不重要。 所以在上面的例子中,[5,3]也是正确的。
您的算法应以线性运行时复杂性运行。 你能实现它只使用恒定的空间复杂性?

思路:

首先比较好想到的还是排序,将这些数排序后相邻两个依次比较,一直比较到第二个没有相同数的值为止,就得到答案了。
当然,还发现这个题和以前做的:http://blog.csdn.net/zzlcsdn2017/article/details/59616340Single Number I(以后称I)有异曲同工之妙,这道题依然是需要用异或来求解:
如果还按I中方式,将所有数字都异或后得到的是其中单独的两个数的异或值,因为这两个数不同,异或后一定存在“1”,而其他值都相互异或为“0”了。那么就可以利用“1”(只用一个就够了,即使可能存在多个,就设定为从低位到高位的第一个“1”,假设为a位)将原来的数组分为两个,一个所有数字a位全是1,另一个是剩下的数字,相同的数字两两都分在了同一个组里,而不同的两个数字也被分开了,最后分别对这两个数组再一次全部异或,便分别得到我们想要的两个数字。

解答:

(94.69%)还是比较强的

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int ax = 0;
    int a = 0, b = 0;
    for (int i = 0; i<nums.size(); i++)
    {
        ax ^= nums[i];
    }
    //for (int item : nums) {
    //  ax ^= item;
    //}
    int lastb = (ax & (ax - 1)) ^ ax;
    for (int item : nums) {
        if (item & lastb) {
            a ^= item;
        }
        else {
            b ^= item;
        }
    }
    /*for (int i = 0; i < nums.size();i++) {
        if (nums[i] & lastb) {
            a ^= nums[i];
        }
        else {
            b ^= nums[i];
        }
    }*/
    return vector<int>{a, b};
    }
};
  1. int lastb = (ax & (ax - 1)) ^ ax;//求二进制ax最小的1所在地。
  2. 第二个for循环直接合并步骤,用if省去了分组的事情,直接将
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值