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

来源:互联网 发布:国密sm2算法 编辑:程序博客网 时间:2024/05/18 02:29

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;
    }


运行结果:


0 0