0
点赞
收藏
分享

微信扫一扫

[LeetCode]Find All Numbers Disappeared in an Array


Question
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]

本题难度Easy。

Set法

【复杂度】
时间 O(N) 空间 O(1)

【思路】
题目要求:Could you do it without extra space and in O(n) runtime。本题有个特点:​​​a[i]==i+1​​​。当然,给的数据不一定按照这个要求,那我们就把它们众神归位,然后凡是不符合这个条件的第i位(其值本应为​​i+1​​​)就把​​i+1​​​放入set。我们利用循环依次考察每个​​a[i]​​,有以下几个情况要分别处理:

  1. ​a[i]==i+1​​。这好办,直接pass
  2. ​a[i]!=i+1​​​。这个情况下,我们在把第i个元素的值​​a[i]​​​送回它老家​​a[a[i]-1]​​​之前,先看看它的老家符不符合要求​​a[a[i]-1]==a[i]​​​,如果符合说明老家已经被占了,间接说明数字​​i+1​​​缺失了,所以把​​i+1​​​放入set,然后考察下一个​​a[i+1]​​​;如果不符合,就进行swap,不过这里并不立刻考察下一个,因为swap过来的这个值可能刚好符合目前这个位置​​a[i]​​,应当交由下一个循环进行再判断。

【注意】
swap有可能是与考察过的位置进行向前交换,需要从set中把该值remove。

【代码】

public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
//require
int size=nums.length;
Set<Integer> set=new HashSet<Integer>();
//invariant
int i=0;
while(i<size){
if(i+1!=nums[i]){
//老家被占了
if(nums[nums[i]-1]==nums[i]){
set.add(i+1); //间接说明i+1缺失了
i++;
}else{
//有可能是向前swap
if(set.contains(nums[i]))
set.remove(nums[i]);
swap(i,nums[i]-1,nums);
}
}else
i++;
}
//ensure
return new LinkedList<Integer>(set);

}
private void swap(int a,int b,int[] nums){
int tmp=nums[a];
nums[a]=nums[b];
nums[b]=tmp;
}
}


举报

相关推荐

0 条评论