原题
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]
Reference Answer
思路分析
已经告诉我们缺少了部分数字,那么我们可以先用set进行去重。然后再次遍历1~N各个数字,然后找出没有在set中出现的数字即可。
必须得用set进行去重,时间复杂度方能通过,若是直接判断
if num not in nums
,超时。
按道理说这种方式依旧开辟了新空间numset
,不满足题意要求,但是依旧能过AC,LeetCode这个设计真是。。蜜汁。。
Code
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
Second Version:
原地变负来标记。比如对于[4, 3, 2, 7, 8, 2, 3, 1],把这些元素作为list的索引,指向的元素变换成负数,那么,没有变换成负数的位置就是没有人指向它,故这个位置对应的下标没有出现。代码如下:
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]
Note
- 想到了用index,但是没想到用set,运行超时;
- 这种不开辟空间,能着手的地方也还有值与索引,结合数组输入长度,找出两者关系,本题将出现数值的地方转换成索引对原数组进行变化,很巧妙地解决了判断未出现值。
参考文献
[1] https://blog.csdn.net/fuxuemingzhu/article/details/53981307