[LeetCode] 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.bash

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

Example:this

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]
複製代碼

解答

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """ :type nums: List[int] :rtype: List[int] """
        for num in nums:
            index = abs(num) - 1
            nums[index] = -abs(nums[index])
        return [i + 1 for i, num in enumerate(nums) if num > 0]
複製代碼

使用一個 dict 解決固然很是容易,相對比較難的是完成題目中的「without extra space and in O(n) runtime」。spa

上面這種解決方案,是將數字和 index 巧妙的作了對應:code

將數組中數字看做下標,而後對應這個「下標」去修改數組中元素的符號;循環一圈後,看哪些位置的符號沒有變更過,就說明原數組裏面沒有這個位置的下標對應的數字。element

相關文章
相關標籤/搜索