136. 只出现一次的数字 leetcode-hot100

38 阅读1分钟

image.png

方法1:异或运算

image.png

当所有数进行异或运算,最终值为唯一值

image.png


class Solution {
    public int singleNumber(int[] nums) {
        int single = 0;
        for (int num : nums) {
            single ^= num;
        }
        return single;
    }
}

方法2:hashmap

  • 第一遍遍历,将数组的数作为key,出现的数量作为value
  • 第二遍遍历,找出value为1的key,则为唯一

image.png

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer i : nums) {
            Integer count = map.get(i);
            count = count == null ? 1 : ++count;
            map.put(i, count);
        }
        for (Integer i : map.keySet()) {
            Integer count = map.get(i);
            if (count == 1) {
                return i;
            }
        }
        return -1; // can't find it.
    }
}