【Lintcode】82. Single Number

题目地址:

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

给定一个含 2 n + 1 2n+1 个数字的数组,其中有且仅有一个数字出现了 1 1 次,别的数都出现了 2 2 次。要求求出那个只出现了一次的数字。

可以利用异或 \wedge 的运算性质来解题。注意到 a a = 0 , a 0 = a a\wedge a=0,a\wedge 0=a ,并且异或满足交换律和结合律(详细证明见https://blog.csdn.net/qq_46105170/article/details/104082406),所以只需将数组中所有数字异或一遍即得到答案。代码如下:

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer
     */
    public int singleNumber(int[] A) {
        // write your code here
        int res = 0;
        for (int i : A) {
            res ^= i;
        }
        return res;
    }
}

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

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

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105263389