Given a non-empty array of integers, each element appears twice except one that appears only once. Find the element that appears only once. 【LeetCode Hot 100】

Question 136 of the Hottest Questions 100:

Paste the code first:

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

    }
}

Problem solving ideas:

This problem requires us to use XOR to solve it. The XOR algorithm conforms to the following:

So when only one element of an array is single, and other elements appear twice, it conforms to the commutative law and associative rate of the XOR operation, for example: 1 ^ 2 ^ 2 ^ 3 ^ 3 ^ 4 ^ 4 = 1; 2^1^3^2^3 = 1;

So we only need to traverse the array once, XOR this number each time, and we can complete the solution.

Guess you like

Origin blog.csdn.net/weixin_56960711/article/details/123340496