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.
给定整数数组,其中元素a[i]满足1 ≤ a[i] ≤ n (n 为数组大小),一些元素出现两次,其他的出现一次。
找出所有范围在[1,n]之间且未在数组中的元素。
请勿使用额外的空间,且在线性时间内完成。可假定返回的列表不算在额外空间内。
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
思路:
利用hash思想,将数字和位置进行联系,利用位置x的数字正负表示数字x是否出现过。这种方法将改变输入数组。
public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res=new ArrayList<>();
for(int i=0;i<nums.length;i++){
int val=Math.abs(nums[i])-1;
if(nums[val]>0) nums[val]=-nums[val];
}
for(int i=0;i<nums.length;i++){
if(nums[i]>0) res.add(i+1);
}
return res;
}
}
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res=[]
for i in range(len(nums)):
val = abs(nums[i])-1
if nums[val]>0: nums[val]=-nums[val]
for i in range(len(nums)):
if nums[i]>0:res.extend([i+1])
return res