1. 程式人生 > 遊戲 >索尼克遊戲版配音辭演 電影版配音表態願意接任

索尼克遊戲版配音辭演 電影版配音表態願意接任

技術標籤:leetcode

2021-02-13 Leetcode每日一題

題目

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]

我的思路:
想麻煩了。知道可以set後查詢沒出現過的數字,但是以為這樣做時間複雜度很高。反而自己直接想半天的方法沒有通過。

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        n = len(nums)
        res = []
        for i in range(1,n+1):
            if i not in set(nums)
: res.append(i) return res

這裡需要補充一下set的排序方式,為什麼這樣時間複雜度反而只有O(n)

提交結果
在這裡插入圖片描述

參考思路:
一個奇淫技巧,原地修改陣列。並沒看太懂。
大概思路是由於每個值都是在[1,n]之間,如果每個數字都出現了一次應該是[1,2,3,4,…,n]這樣的一個數組。當nums[i] = x,那麼這個值應該放在下標為x-1的位置,可以標記它為負表示它在這個數組裡出現過了。而對於已經為負值的數可以先取其絕對值,還原成原本的數之後再修改nums[x-1]。最終再次遍歷找到仍為正的數字-1則是沒有出現過的數字。
使用這種方法的原因是每個值都在[1,n]之間,因此標記的時候只要把每個值標記為不在這個區間內的數值,因此也可以選擇+n。

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