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.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]
解法1:Brutal force(TLE)
遍历1到n的每个数,检查这个数在list中有没有出现
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
for i in range(1,len(nums)+1):
if i not in nums:
ans.append(i)
return ans
时间复杂度:O(n^2), 需要检查n个数字,每次检查复杂度为O(n)
空间复杂度:O(1)
解法2:Hashmap
将出现过的数字存入hashmap中,利用hashmap查找复杂度为O(1)的特性来实现整个算法复杂度O(n).
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
memo = {}
for num in nums:
memo[num] = num
ans = []
for i in range(1,len(nums)+1):
if i not in memo:
ans.append(i)
return ans
时间复杂度:O(n)
空间复杂度:O(n),这边空间复杂度不符合题目要求
解法3:利用input数组储存信息
对于每个出现过的数字,以这个数字作为index,将相应index位置的数字变换符号,以此来mark出现过的数组。所以每个为负的数字所在的位置的index出现过,为正则没有出现。需注意一个问题,**由于在遍历过程中,后面的数字可能已经为负,所以每个数字需要取绝对值来做index
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for num in nums:
if nums[abs(num)-1]>0:
nums[abs(num)-1]*=-1
ans = []
for i in range(1,len(nums)+1):
if nums[i-1] > 0:
ans.append(i)
return ans
时间复杂度:O(n)
空间复杂度:O(1)