天天看点

LeetCode 448. Find All Numbers Disappeared in an Array448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

题目

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

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

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

示例

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

输出:
[5,6]
           

代码

用python中的集合set()函数,能够得到列表中不重复的元素集合。

class Solution:
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        l1 = len(nums)
        l3 = []
        for i in range(l1):
            l3.append(i+1)
        num = list(set(l3) - set(nums))
        return [i for i in num]
           

讨论区学习

不用额外空间的解法:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in range(len(nums)):
            x = abs(nums[i])
            nums[x-1] = -1*abs(nums[x-1])
        return [i+1 for i in range(len(nums)) if nums[i]>0]
           

这个方法运用了绝对值把列表内容和位置联系起来,怎么表示这个列表里有4呢,就把下表为3的地方的值置为负的原绝对值,即-7,保留了7存在的信息,这样扫过一遍只有下标为4和5的地方没有被置为负,因为不存在5和6这两个数,再扫一遍把值为正的下标输出出来即可。