⛅82. 落单的数

2020.07.23 LintCode

题目描述

给出 2 * n + 1个数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。(n≤100)

示例

样例 1:

输入:[1,1,2,2,3,4,4]
输出:3
解释:
仅3出现一次
样例 2:

输入:[0,0,1]
输出:1
解释:
仅1出现一次

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

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer
     */
    public int singleNumber(int[] A) {
        // write your code here
        HashSet<Integer> hashset = new HashSet<>();
        for (int a:A){
            if(hashset.contains(a)){
                hashset.remove(a);
            }else{
                hashset.add(a);
            }
        }
        return hashset.iterator().next();
    }
}

猜你喜欢

转载自www.cnblogs.com/charlottepl/p/13369150.html