zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    ES数据-MySql处理Date类型的数据导入处理
    es搜索引擎
    Java Web学习路线
    九樱天下-观察期
    一些平常的总结
    ES搜索引擎-简单入门
    工作中异常的一些总结
    抽象和封装的一点总结
    python之路_django分页及session介绍
    python之路_django中母板及cookie介绍
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10706197.html
Copyright © 2011-2022 走看看