Lintcode—落单的数

来源:互联网 发布:q币拦截软件 编辑:程序博客网 时间:2024/05/01 10:11

落单的数(Java)

题目

给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。

输入:

[1,1,2,3,3,3,2,2,4,1]

输出:

4

要求:

一次遍历,常数级的额外空间复杂度

思路:

把数组中所有的数字做异或,因为相同的两个数组异或结果为0,所以最后得到的数字就是结果。

Java代码:

public class Solution {    /**     *@param A : an integer array     *return : a integer      */    public static int singleNumber(int[] A) {        if (A.length == 0) {            return 0;        }        int res = A[0];        for(int i = 1; i < A.length; i++){            res = res ^ A[i];        }        return res;    }}
0 0
原创粉丝点击