[LeetCode] 136. The number appears only once

Topic links: https://leetcode-cn.com/problems/single-number/

Subject description:

Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.

Description:

Your algorithm should have linear time complexity. You can not use the extra space to achieve it?

Example:

Example 1:

输入: [2,2,1]
输出: 1

Example 2:

输入: [4,1,2,1,2]
输出: 4

Ideas:

XOR on it

def singleNumber(self, nums: List[int]) -> int:
        res = nums[0]
        for num in nums[1:]:
            res ^= num
        return res

java

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

Guess you like

Origin www.cnblogs.com/powercai/p/11209446.html