(掘金刷题)1 - 找单独的数

56 阅读1分钟

问题描述

在一个班级中,每位同学都拿到了一张卡片,上面有一个整数。有趣的是,除了一个数字之外,所有的数字都恰好出现了两次。现在需要你帮助班长小C快速找到那个拿了独特数字卡片的同学手上的数字是什么。

要求:

  1. 设计一个算法,使其时间复杂度为 O(n),其中 n 是班级的人数。
  2. 尽量减少额外空间的使用,以体现你的算法优化能力。

题解:

    public static int solution(int[] cards) {
        HashSet<Integer> set = new HashSet<Integer>();
        int ans = 0;
        for(int i = 0 ; i < cards.length ; i++ ){
            if(set.contains(cards[i])){
                ans -= cards[i];
            }else{
                set.add(cards[i]);
                ans += cards[i];
            }
        }
        return ans;
    }