leetcode 数据结构—只出现一次的数字_官网

 

这题如果用一般数据结构来解决,存在很多种解法,比如:通过hashmap记录出现的次数,最后遍历得到次数为1的数。或者通过hashset添加数字,如果无法添加就删除该数字。

    public int singleNumber(int[] nums) {
        Set<Integer> hset=new HashSet<>();
        for(int i=0;i<nums.length;i++)
        {
            if(hset.add(nums[i]))
                continue;
            else
                hset.remove(nums[i]);
        }
        return hset.iterator().next();
    }

官网上还给了一种用异或解答的方法,因为异或的交换律,最终我们遍历数字对每个元素进行异或操作,最后就只会剩下那个只出现一次的元素。

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