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.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

这里有两个不同的数只出现过1次,一路异或过去,出现两次的数异或结果变成0,剩下的数是两个target之间有差异的位,换句话说一个数是0,另一个数的对应位就是1。用diff &= -diff能得到最后一位1。然后用这个特殊位分离开两个数。举个例子:

二进制数,正负数互换,则要把全部数码(包括符号位)都求反加1。
+5:0101
-5:1010+1 = 1011

+5 & -5 = 0001

代码如下:

public class Solution {
    public int[] singleNumber(int[] nums) {
        int diff = 0;
        for (int num: nums) {
            diff ^= num;
        }
        diff &= -diff;
        int target1 = 0, target2 = 0;
        for (int num: nums) {
            if ((num & diff) == 0) {
                target1 ^= num;
            } else {
                target2 ^= num;
            }
        }
        return new int[]{target1, target2};
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值