[Bit Operation-Simple] 136. Numbers that only appear once (Bit Operation + Sorting + One Line of Code)

【topic】

[Code]
[Python]
Insert picture description here

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        for i in range(1,len(nums)):
            nums[0]^=nums[i]
        return nums[0]

【Sort + Count】
Insert picture description here

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        nums.sort()
        flag=0
        for i in range(1,len(nums)):
            if nums[i]==nums[i-1]:
                flag+=1
            else:
                flag-=1
            if flag<0:
                return nums[i-1]
        return nums[-1]

[One line of code: reduce + bit operation]
Insert picture description here

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(lambda x, y: x ^ y, nums)

Guess you like

Origin blog.csdn.net/kz_java/article/details/115051793