448.Find All Numbers Disappeared in an Array

Tags: [swap]

Link: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/?tab=Description

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]

Solution: swap

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []

        index = 0
        while index < len(nums):
            curr = nums[index]
            if curr == index + 1 or curr == nums[curr - 1]:
                index += 1
                continue

            nums[index], nums[curr - 1] = nums[curr - 1], nums[index]

        result = []
        for i in xrange(len(nums)):
            if i + 1 != nums[i]:
                result.append(i + 1)

        return result

Revelation:

  • When we need solve the problem that there exists the relationship between the element's value and the element's index, we can think about using the swap to solve the problem.

Note:

  • Time complexity = O(n), n is the number of elements of the given array.

results matching ""

    No results matching ""