LeetCode260 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:

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?

这次的问题变成special的数又两个了,实际上题目并不是找single number了,而是找special two number。所以之前两个题目的解法是不适用的,起码不是直接适用的。如果可以把two number的问题变成两个single number的问题,就可以套用之前第一个问题的解法了,也就是说我们可以通过某种方式把数组分为两组,每组只包含那两个special number中的一个。

问题的关键就变成如何分组了。思路也是有点巧妙,考虑到两个special number是不一样的,而恰好其余的数都是出现两次,所以如果对每个数都做亦或操作,最后的结果就是那两个special number的亦或,而且至少有一个位是1,那么就可以根据其中一个为1的位将所有的数分为两组,再套用第一个题的方法即可。

public int[] singleNumber(int[] nums) {
    int diff = 0;
    for(int num: nums){
        diff^=num;
    }
    diff = Integer.highestOneBit(diff);//作用是取这个数的二进制形式最左边的最高一位且高位后面全部补零,最后返回int型的结果。

    int[] result = new int[2];
    Arrays.fill(result,0);
    for(int num: nums){
        if((diff & num) == 0){
            result[0] ^= num;
        }
        else{
            result[1] ^= num;
        }
    }
    return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值