1. 程式人生 > >LeetCode448:Find All Numbers Disappeared in an Array

LeetCode448:Find All Numbers Disappeared in an Array

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]

LeetCode:連結

LeetCode442:Find All Duplicates in an Array其實就是一樣的。

第一種方法:將nums[i]置換到其對應的位置nums[nums[i]-1]上去,比如對於沒有缺失項的正確的順序應該是[1, 2, 3, 4, 5, 6, 7, 8],而我們現在卻是[4,3,2,7,8,2,3,1],我們需要把數字移動到正確的位置上去,比如第一個4就應該和7先交換個位置,以此類推,最後得到的順序應該是[1, 2, 3, 4, 3, 2, 7, 8],我們最後在對應位置檢驗,如果nums[i]和i+1不等,那麼我們將i+1存入結果res中即可。

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in range(len(nums)):
            '''直接就奔著能不能換到交換的位置上去'''
            while nums[nums[i]-1] != nums[i]:
                nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
        result = []
        for i in range(len(nums)):
            if i + 1 != nums[i]:
                result.append(i+1)
        return result

第二種方法:對於每個數字nums[i],如果其對應的nums[nums[i] - 1]是正數,我們就賦值為其相反數,如果已經是負數了,就不變了,那麼最後我們只要把留下的整數對應的位置加入結果res中即可。其實就是用正負標誌位,區分出現的元素和未出現的元素,只標記,不交換

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in range(len(nums)):
            j = abs(nums[i]) - 1
            nums[j] = -abs(nums[j])
        return [i + 1 for i in range(len(nums)) if nums[i] > 0]