LeeCode136 numbers that appear only once (Java) (exclusive OR and array)

Title link: Numbers that appear only once in LeeCode136
Title description: The way Insert picture description here
I think is to sort them one by one. If the current one is equal to the previous element, then set the flag to true. When the flag is true, it can go forward even if it is not equal. Go, find the point that is neither flag equal to the previous element nor false is a single element

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        Arrays.sort(nums);
        boolean flag=false;
        int index=1;
        while (index < nums.length) {
    
    
            if(nums[index-1]==nums[index]){
    
    
                flag=true;
            }else {
    
    
                if(flag){
    
    
                    index++;
                    flag=false;
                    continue;
                }else{
    
    
                    return nums[index-1];
                }
            }
            index++;
        }
        return nums[index-1];
    }
}

Then the efficiency was 50%, and I looked for a solution to the problem, which was stupid. . . . It will make me think that my life will be wasted

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        for (int i = 1; i < nums.length; i++) {
    
    
            nums[0]^=nums[i];
        }
        return nums[0];
    }
}

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/113063568