• 11.Find All Numbers Disappeared in an Array(找出数组中缺失的数)


    Level:

      Easy

    题目描述:

    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]
    

    思路分析:

      题目要求在长度为n的数组中找到缺失的数字,数组中的元素大小在1-n。算法的时间复杂度要求在O(n),我们可以对数组进行一个原地排序,如果nums[i]不等于i+1,并且nums[i]!=nums[nums[i]-1],那么我们就交换num[i]和nums[nums[i]-1]。对整个数组遍历完成后,我们重新遍历数组,如果nums[i]不等于i+1,那么i+1就是缺失的数字。

    代码:

    class Solution {
        public List<Integer> findDisappearedNumbers(int[] nums) {
            ArrayList<Integer>res=new ArrayList<>();
            for(int i=0;i<nums.length;i++){
                while(nums[i]!=i+1&&nums[nums[i]-1]!=nums[i]){
                    int temp=nums[i];
                    nums[i]=nums[temp-1];
                    nums[temp-1]=temp;
                }
            }
            for(int i=0;i<nums.length;i++){
                if(nums[i]!=i+1)
                    res.add(i+1);
            }
            return res;
        }
    }
    
  • 相关阅读:
    luogu P2661 信息传递 强连通分量求最小环
    luogu P1346 电车 最短路
    luogu P1113 杂务
    luogu P1111 修复公路 最小生成树prim
    python提交要注意的几个地方
    【图论】拓扑排序
    算法竞赛入门经典 第六章
    实用函数
    Markdown数学公式语法
    Codeforces Round #627 (Div. 3) 补题
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10706197.html
Copyright © 2020-2023  润新知