[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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值