LeetCode:260. Single Number III

30 篇文章 0 订阅
21 篇文章 0 订阅

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?

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

题意:给定数组中有且只有两个数只出现1次,其他数全部出现2次,找出这两个数。
分析:找出出现1次的数,首先想到异或操作,然而存在两个只出现1次的数,那就要想办法把这两个数分开。因为这两个数不同(如果相同,那么都出现两次),说明两个数的二进制表示中至少有一位是不相同,如果根据该位将数组分成两部分,然后分别异或,那么两组的异或结果便是这两个数。那么如何找到二进制不同的位呢?可以先对整个数组异或,结果必然不是0,只要找到这个异或结果的某一非0位,即是两个数不同的位。
代码如下:

class Solution {
    public int[] singleNumber(int[] nums) {
        int n=0;
        for(int i=0;i<nums.length;i++){
            n=n^nums[i];
        }
        int m=1;
        while((n&m)==0) m=m<<1;
        n=0;
        int n2=0;
        for(int i=0;i<nums.length;i++){
            if((nums[i]&m)==0){
                n=n^nums[i];
            }
            else
                n2=n2^nums[i];
        }
        int[] result=new int[2];
        result[0]=n;
        result[1]=n2;
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值