代碼一:數組
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