python-leetcode-448. 找到所有数组中消失的数字(题解)

题目描述

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

解法一:

  • 将所有正数作为数组下标,置对应数组值为负值。那么,仍为正数的位置即为(未出现过)消失的数字。

  • 举个例子:

        原始数组:[4,3,2,7,8,2,3,1]
        重置后为:[-4,-3,-2,-7,8,2,-3,-1]
    
  • 结论:[8,2] 分别对应的index为[5,6](消失的数字)

# 时间复杂度O(2n),空间复杂度 $O(1)$,res 不算额外空间
class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for num in nums:
            index = abs(num) - 1
            # 始终保持nums[index]为负数
            nums[index] = -abs(nums[index])
        return [i + 1 for i, num in enumerate(nums) if num > 0]

解法二:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        s = set(nums)
        return [i+1 for i in range(len(nums)) if (i+1) not in s]

解法三:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        return list(set(range(1, len(nums)+1)) - set(nums))

解法四:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = []
        newnums = set(nums)
        for i in range(1, len(nums) + 1):
            if i not in newnums:
                res.append(i)
        print(newnums, len(nums))
        return res
发布了67 篇原创文章 · 获赞 6 · 访问量 9934
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章