448. 找到所有数组中消失的数字

 

sorted()函数返回值:排好序的list——set经sorted()后也返回list。

sorted()和sort()理解与区别详见:https://www.cnblogs.com/panweiwei/p/12712756.html

代码一:

 1 class Solution(object):
 2     def findDisappearedNumbers(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[int]
 6         """
 7         # 返回值
 8         ans = []
 9         # 去重升序
10         s = sorted(set(nums))
11         index = 0
12         # 遍历整数1到n
13         # range[start,end):左闭右开
14         for i in range(1, len(nums)+1):
15             if index < len(s) and i == s[index]:
16                 index += 1
17             # 若i不在原数组中,则添加到返回值中
18             else:
19                 ans.append(i)
20         return ans

代码二,超时:

 1 class Solution(object):
 2     def findDisappearedNumbers2(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[int]
 6         """
 7         ans = []
 8         n = len(nums)
 9         for i in range(1, n + 1):
10             if i not in nums:
11                 ans.append(i)
12         return ans
原文地址:https://www.cnblogs.com/panweiwei/p/12757666.html