448. 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]

Thoughts:

  1. mark the value indexed by current value as negative
  2. add all index whose number is not negative (since originally 1 ≤ a[i] ≤n(n= size of array)
class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        # negating the number indexed by the value
        for i in range(len(nums)):
            idx = abs(nums[i]) - 1
            if(nums[idx] > 0):
                nums[idx] = -nums[idx]
        res = []
        for i in range(len(nums)):
            if(nums[i] > 0):
                res.append(i + 1)
        return res
class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for num in nums:
            i = abs(num) - 1
            if nums[i] > 0:
                nums[i] = -nums[i]

        return [i + 1 for i in range(len(nums)) if nums[i] > 0]

results matching ""

    No results matching ""