[LC260]Single Number III

来源:互联网 发布:哪个搜索软件好 编辑:程序博客网 时间:2024/04/19 10:16

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?

这道题是 single number I 的升级,区别是出现了两个只出现一次的数字。

依旧使用 bit manipulate 的思想,首先,假如我们使用和题1一样的方法,结果会是什么?

结果将是两个数的异或结果

以题目中的例子为例,最后将会是 011 ^ 101 = 110

那么如何区分这两个数字呢?

首先我们可以确定这两个数必然不是一样的,那么,必将存在一位两数不同,体现在 xor 的结果上,就是必然存在一个为1的位数。从左往右或者从右往左并不影响,假如我们从右往左数,第一个出现1的是十位。

这样我们就能够把整个数列区分为两类,一类是十位为1的,一类是十位为0的,每一类存在一个 single number,其余数字均出现两次,于是利用 single number1的方法就可以得到两个 single number

public class Solution {    public int[] singleNumber(int[] nums) {        int[] res = new int[2];        int xor = 0;        for(int num:nums){            xor ^= num;        }        int ind = 0;        for(int i = 31; i >= 0; i--){            if(( (xor>>i) & 1) == 1){                ind = i;                break;            }        }        int ans1 = 0, ans2 = 0;        for(int num:nums){            if(((num>>ind)&1) == 0){                ans1 ^= num;            }else{                ans2 ^= num;            }        }        res[0] = ans1;        res[1] = ans2;        return res;    }}
0 0
原创粉丝点击