LeetCode 题解(189): 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?
题解:

扫两遍,第一遍全异或得值temp。取temp中最低位不为0的位,其余位置0。如temp = 6 = 0x110,则取0x010。

扫第二遍,所有 i & 0x010 == 0x010的数异或得一个结果,其余数异或得另一个结果。

原理是两个不同的数至少会有一个bit位不同,造成全异或的结果中至少一位为1.那么以该位做区分,即可得两数。

C++版:

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        vector<int> result(2, 0);
        int temp = 0;
        for(auto i : nums)
            temp ^= i;
        int i = 1;
        while((temp & i) != i)
            i = i << 1;
        for(auto j : nums) {
            if((j & i) == i)
                result[0] ^= j;
            else
                result[1] ^= j;
        }
        return result;
    }
};

Java版:

public class Solution {
    public int[] singleNumber(int[] nums) {
        int[] result = new int[2];
        int temp = 0;
        for(int i = 0; i < nums.length; i++)
            temp ^= nums[i];
        int j = 1;
        while((temp & j) != j)
            j <<= 1;
        for(int i = 0; i < nums.length; i++) {
            if((nums[i] & j) == j)
                result[0] ^= nums[i];
            else
                result[1] ^= nums[i];
        }
        return result;
    }
}

Python版:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        result = [0, 0]
        temp = 0
        for i in nums:
            temp ^= i
        j = 1
        while temp & j != j:
            j <<= 1
        for i in nums:
            if i & j == j:
                result[0] ^= i
            else:
                result[1] ^= i
        return result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值