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

  • 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?

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


分析

参考:LeetCode 136 Single Number
参考:LeetCode 137 Single Number II

“相异为1”,所以一个数字异或本身为0,而0异或0仍为0, 一个数字异或0仍为这个数字。

0 ^ 0 = 0 
n ^ 0 = n 
n ^ n = 0

  1. 只有两个数a、b分别出现了一次,其余的数都是出现了两次
  2. 把整个数组异或,结果等于a^b,而a与b是不相等的,所以a^b必不为0
  3. 按照a^b结果其中一位,把数组分成两个,一组包含a,一组包含b,即问题变成LeetCode 136 Single Number

代码

    public int[] singleNumber(int[] nums) {

        int[] rt = new int[2];

        int n = 0;

        for (int v : nums) {
            n ^= v;
        }

        int m = n & (~(n - 1));

        for (int v : nums) {
            if ((m & v) == 0) {
                rt[0] ^= v;
            } else {
                rt[1] ^= v;
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值