描述
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.
每日格言:过去属于死神,未来属于你自己。