leetcode 136 只出现一次的数字

原题点这里

统计只出现一次的数字

这个很容易想到用 map或set做。

public int singleNumber(int[] nums) {
        int n = nums.length;
        HashSet<Integer> record = new HashSet<>();
        for(int i=0;i<n;i++){
            if(record.contains(nums[i])){
                record.remove(nums[i]);
            }else{
                record.add(nums[i]);
            }
        }
        for(Integer ans : record){
            return ans;
        }
        return 0;
    }
View Code

我们知道,任何数 异或 0 = 它本身

任何数 异或 它本身 =0

利用这个性质,可以利用位运算优雅的解题。

int n = nums.length;
        int ans = 0;
        for(int i=0;i<n;i++) {
            ans^=nums[i];
        }
        return ans;
View Code
原文地址:https://www.cnblogs.com/superxuezhazha/p/12886943.html