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]
题目大意: 给定一组范围内的数列,但是会有缺少,返回这个缺少的值。 有特别限制,不要开拓新的空间。
思路一:
暴力解题,一个一个对比。但是没有满足开拓新空间的限制。不过可以用在平时的工作个生活中。
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
checklist = list(range(1,len(nums)+1)) #从1开始,生成这个范围内的有序数列。
returnlist = []
for i in nums:
checklist[i-1] = 0 #nums中有那个,我就在生成的数列中去掉哪个(使其变成0)。
for i in checklist:
if i != 0:
returnlist.append(i) #在生成的数列中剩下的元素,即为所求的元素,放到一个数列中并返回。
return returnlist
思路二: (python的魅力)
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
return list(set(range(1,len(nums)+1)) - set(nums))
直接返回,让两个集合相减。Python作为脚本语言的优势就在这儿!万物皆对象! 不过set集合相减这里,底层有没有开拓新的空间,存疑。 Submissions如下。
Runtime: 352 ms, faster than 96.17% of Python3 online submissions for Find All Numbers Disappeared in an Array.
Memory Usage: 24.9 MB, less than 7.14% of Python3 online submissions for Find All Numbers Disappeared in an Array.
以空间换效率了。
思路三:
也是学来的,原地做负标记,同理除了做负其他任何标记应该都可以。abs方法,返回函数的绝对值。 效率一般,还不如上一个思路,不过觉得这个变做负的标记方式很巧妙!
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
for i in range(len(nums)): #在一个新的有序数组里遍历
index = abs(nums[i]) - 1 # i-1 变成位置索引。 因为python计数是从0开始的。
nums[index]= - abs(nums[index]) #把每一个数都变负。因为index是有序数列,所以可以筛选出来重复的数字。
return (i+1 for i in range(len(nums)) if nums[i]>0) #重复的数字有一个没有变负,所以从位置索引+1往后顺延一个就是缺少的元素。
2020/04/07
疫情中的英国,
每天好几十个人看我写的分享,还是挺有成就感的。
加油!