動機

這題很經典,在programming pearls有出現過

Problem

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

 

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]Output: [5,6]

Example 2:

Input: nums = [1,1]Output: [2]

 

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • 1 <= nums[i] <= n

 

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Sol

注意到內容物如果排序完,會與對應的index差一

可以利用這個特性,把目前不適合的換到適合的位置,一路換到最後 之後就是直接看有哪個不是內容物與index差一的就是要找的

這種在同一個位置一直換換是個經典的手法,很有趣

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            while nums[i]-1 != i and nums[nums[i]-1] != nums[i]:
                tmp = nums[i]
                nums[i] = nums[tmp-1]
                nums[tmp-1] = tmp
        ret = []
        for i in range(len(nums)):
            if nums[i]-1 != i:
                ret.append(i+1)
        return ret