leetcode 448. Find All Numbers Disappeared in an Array( Python )

描述

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

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

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:app

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

Output:
[5,6]
複製代碼

解析

就是有一個包含 1 到 n 的數字列表中,缺乏哪些數字,直接用 set 計算差集便可,時間複雜度 O(N),空間複雜度 O(N)。less

解答

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.
複製代碼

每日格言:過去屬於死神,將來屬於你本身。yii

感謝支持
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索