136. Single Number刷题笔记

暴力遍历导致超时

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        i = 0
        j = 1
        while i<len(nums):
            while j<len(nums):
                if nums[j]==nums[i]:
                    nums[i+1],nums[j] = nums[j],nums[i+1]
                    i += 2
                    j = i+1
                else:
                    j += 1
            if j==len(nums):
                return nums[i]

用异或,可以解决这个问题

reduce是迭代方法,第0和第1元素操作的结果和第2元素继续操作,以此类推

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(operator.xor, nums)

136. Single Number刷题笔记_第1张图片

你可能感兴趣的:(LeetCode,Python刷题,leetcode,算法,动态规划)