利特代码448。查找数组中消失的所有数字(python),leetcode448FindAllNumbersDisappearedinanArraypython

发表时间:2020-12-25

描述

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

解析

就是有一个包含 1 到 n 的数字列表中,缺少哪些数字,直接用 set 计算差集即可,时间复杂度 O(N),空间复杂度 O(N)。

解答

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

运行结果

Runtime: 320 ms, faster than 89.85% of Python online submissions for Find All Numbers Disappeared in an Array.
Memory Usage: 20.6 MB, less than 30.78% of Python online submissions for Find All Numbers Disappeared in an Array.

每日格言:过去属于死神,未来属于你自己。

文章来源互联网,如有侵权,请联系管理员删除。邮箱:417803890@qq.com / QQ:417803890

微配音

Python Free

邮箱:417803890@qq.com
QQ:417803890

皖ICP备19001818号
© 2019 copyright www.pythonf.cn - All rights reserved

微信扫一扫关注公众号:

联系方式

Python Free