LC 260. Single Number III 位运算解法

Description

Given an integer array 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. You can return the answer in any order.

Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

Example 1:

Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
Example 2:

Input: nums = [-1,0]
Output: [-1,0]
Example 3:

Input: nums = [0,1]
Output: [1,0]

Solution

重点: 两个相同元素 异或 == 0

这题的重点先把所有元素 ^ 求出两个出现一次元素的异或值,这里我们称为 re,re代表两个出现一次元素的位运算的不同值。比如 010 和 011 的异或值是 001,表明右边第一位取值不同。这个时候我们把所有元素的右边第一位进行计算,如果是 1 则和 a(初始为0) 异或, 如果是 0 则和 b(初始为0) 异或。这样就成功把两个出现一次的元素分散到两个不同的地方异或了。又因为两个相同的元素异或 == 0, 所以 a和b就是所求值。


    public int[] singleNumber(int[] nums) {
        if (nums.length <= 2) return nums;
        int re = 0;
        for (int i : nums)
            re ^= i;
        int i = 0;
        while (((re >> i) & 1) != 1)
            ++i;
        int a = 0, b = 0;
        for (int n : nums) {
            if (((n >> i) & 1) == 1)
                a ^= n;
            else
                b ^= n;
        }
        return new int[]{a, b};
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值