做者: 负雪明烛
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/python
[LeetCode]app
题目地址:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ide
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进行去重。而后再次遍历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 日 —— 这么快就到双十一了??