1. 程式人生 > 其它 >leetcode 448. Find All Numbers Disappeared in an Array(python)

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

技術標籤:leetcodeleetcode

描述

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.

每日格言:過去屬於死神,未來屬於你自己。