【Lintcode】84. Single Number III

题目地址:

https://www.lintcode.com/problem/single-number-iii/description

给定一个数组,其中有且仅有两个数各自出现了 1 1 次,其余数都出现了 2 2 次,要求将那两个出现了 1 1 次的数求出来。

基本思路是,假设所要求的两个数分别是 a a b b ,那么先将所有数异或一遍得 u = a b u=a\wedge b ,其必定非零,否则就会得出 a = b a=b 的结论,就矛盾了。接着求出 u u 的lowbit(参考https://blog.csdn.net/qq_46105170/article/details/104082406),就可以将数组中的数 x x 按照 x l o w b i t ( u ) x\wedge lowbit(u) 是否为 0 0 分为两类,再在这两类中做异或,就可以筛选出所要求的两个数了。代码如下:

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer array
     */
    public List<Integer> singleNumberIII(int[] A) {
        // write your code here
        int axorb = 0;
        for (int i : A) {
            axorb ^= i;
        }
        
        int lowb = lowbit(axorb);
        int a = 0, b = 0;
        for (int i : A) {
            if ((i & lowb) != 0) {
                a ^= i;
            } else {
                b ^= i;
            }
        }
        
        return Arrays.asList(a, b);
    }
    
    private int lowbit(int x) {
        return x & (-x);
    }
}

时间复杂度 O ( n ) O(n) ,空间 O ( 1 ) O(1)

发布了354 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105264331
今日推荐