欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Single Number III

程序员文章站 2022-05-02 19:09:15
...
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?

给定一个数组,里面有两个数字出现了一次,其他都出现了两次,找出这两个元素,要求在线性时间内完成。我们用位运算来完成,首先将数组中所有的元素进行异或运算得到一个值helper,然后用helper & (~(helper - 1)) 这样就得到了一个某一位为1其他位全为0的数tell,并且1所在的位上两个单独出现的数肯定不同。我们通过tell将数组中的元素分为两部分,分别与tell进行位与运算,最终得到两个单独的数。代码如下:
public class Solution {
    public int[] singleNumber(int[] nums) {
        if(nums == null || nums.length < 2) return new int[0];
        int helper = 0;
        for(int i = 0; i < nums.length; i++) {
            helper ^= nums[i];
        }
        int tell = helper & (~(helper - 1));
        int single1 = 0;
        int single2 = 0;
        for(int i = 0; i < nums.length; i++) {
            if((nums[i] & tell) == 0) {
                single1 ^= nums[i];
            } else {
                single2 ^= nums[i];
            }
        }
        int[] result = {single1, single2};
        return result;
    }
}
相关标签: 位运算

上一篇: Reverse Bits

下一篇: Single Number II