【LeetCode】448. Find All Numbers Disappeared in an Array 解題報告(Python)

做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/python


[LeetCode]app

題目地址:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ide

  • Total Accepted: 14302
  • Total Submissions: 24993
  • Difficulty: Easy

題目描述

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.this

Find all the elements of [1, n] inclusive that do not appear in this array.spa

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

Example:索引

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

Output: [5,6]

題目大意

方法一:暴力求解

剛開始沒想到頗有效的方法,只能用暴力解決。但這個方法不符合題目沒有額外空間的要求。element

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """ :type nums: List[int] :rtype: List[int] """
        cList = list(range(1, len(nums) + 1))
    	returnList = []
    	for x in nums:
    		cList[x - 1] = 0
    	for x in cList:
    		if x != 0:
    			returnList.append(x)
    	return returnList

AC:359 msleetcode

方法二:原地變負作標記

參考了別人的,我學會了一種方法:原地變負來標記。好比對於[4, 3, 2, 7, 8, 2, 3, 1],把這些元素做爲list的索引,指向的元素變換成負數,那麼,沒有變換成負數的位置就是沒有人指向它,故這個位置對應的下標沒有出現。get

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

AC:362 ms

這個速度仍然不理想。

方法三:使用set

已經告訴咱們缺乏了部分數字,那麼咱們能夠先用set進行去重。而後再次遍歷1~N各個數字,而後找出沒有在set中出現的數字便可。

Python代碼以下,戰勝96%.

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """ :type nums: List[int] :rtype: List[int] """
        res = []
        numset = set(nums)
        N = len(nums)
        for num in range(1, N + 1):
            if num not in numset:
                res.append(num)
        return res

日期

2017 年 1 月 2 日 2018 年 11 月 10 日 —— 這麼快就到雙十一了??