【Leetcode】448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

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]

Subscribe to see which companies asked this question

题目简述:

题目的大意是给你一个n长的数组,数组中数据是[1,n]。需要你求出哪些[1,n]的数没出现。要求算法复杂度为O(n),不能开辟额外的空间(输出开辟的不算额外空间)

思路分析:

为了不开辟额外的空间,将数组的下标利用起来,用来标识一个数是否出现过。首先,读入数组第一个值x,我们可以将数组中x-1位置标识为-1,标识x出现过。同时,在标识之前存下x-1位置的值,再标识完之后利用之前存下的值重复以上过程。

以上的过程很可能没办法遍历整个数组,我们再遍历整个数组。如果标识为-1则跳过,否则进入上面的迭代。这样,最后数组对应位置不为-1就表示该数缺失。

算法复杂度O(n)


代码:

    public List<Integer> findDisappearedNumbers(int[] nums) {
        int temp,loc=0;
        List<Integer> aArray = new ArrayList<Integer>();
        int step=0;
        //temp = nums[step];
        while(step<nums.length){
            temp = nums[step++];
            while(temp!=-1){
                //temp = nums[loc];
                loc = nums[temp-1];
                nums[temp-1] = -1;
                temp = loc;
            }
            //step++;
        }
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=-1){
                aArray.add(i+1);
            }
        }
        return aArray;
    }


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值