【LeetCode】448. 找到數組中沒有出現的元素

問題描述

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.

給定一個整數數組,其中 1 ≤ a[i] ≤ n (n = 數組大小),有些元素出現兩次,有些元素出現一次。
找到 [1, n] 中不出現在這個數組中的所有元素。
你能在 O(n) 運行時不需要額外的空間嗎?你可以假定返回的列表不算作額外的空間。

輸入:
[4,3,2,7,8,2,3,1]

輸出:
[5,6]

Python 實現

從題目條件可以知道,數組中的元素可以與數組索引形成一個對應關係。舉個理想的情況,一個長度爲n的數組,其索引爲 0 到 n-1,其元素爲 1 - n。這樣子索引與元素值之間的關係就是:索引 + 1 = 元素值。因此,我們可以通過數組中出現的元素值對相應索引對應的值進行標記,最後沒有被標記的索引位置,相應的就是沒有出現的元素。

具體做法是:

  • 通過一次遍歷,將以出現元素的值減 1 爲索引的元素乘 -1;
  • 沒有出現過的元素,對應 -1 的索引位置的值仍然爲正數。
class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        
        # Marked the index with element by multiplying -1.
        for idx in range(len(nums)):
            num = nums[idx]
            if nums[abs(num)-1] > 0:
                nums[abs(num)-1] *= -1
            
        # The indeces of remain positive numbers, adding one, are the targets.
        ret_list = []    
        for idx in range(len(nums)):
            if nums[idx] > 0:
                ret_list.append(idx+1)
        
        return ret_list

鏈接:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章