ZhongKuo0228 / study

0 stars 0 forks source link

136. Single Number #123

Open fockspaces opened 6 months ago

fockspaces commented 6 months ago

The two rules:

  1. a XOR a = 0
  2. 0 XOR a = a

so if there's pair numbers in list, we can simply eliminate it by XOR and get the single exist number by initialize the ans as 0.

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