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;
}

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/84952817
今日推荐