zoukankan      html  css  js  c++  java
  • 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]

    给定一个整数数组,其中1 ≤ a[i] ≤ n (n = 数组长度),一些元素出现两次,其他的出现一次。

    寻找所有[1, n]中没有出现在数组中的元素。

    可以不使用额外空间并在O(n)运行时间求解吗?你可以假设返回列表不算额外空间。

     思路:直接在原数组上遍历。如果出现过,将其本来应该在的位置设置为负值。最后遍历,为正的即为缺失值

     1     public List<Integer> findDisappearedNumbers(int[] nums) {
     2          List<Integer> result = new ArrayList<>();
     3         for (int i=0;i<nums.length;i++)
     4         {
     5             int val = Math.abs(nums[i]) - 1;
     6             if(nums[val] > 0) {
     7                 nums[val] = -nums[val];
     8             }
     9         }
    10         for(int i = 0; i < nums.length; i++) {
    11             if(nums[i] > 0) {
    12                 result.add(i+1);
    13             }
    14         }
    15         return result;       
    16     }

     类似题目: 

    442. Find All Duplicates in an Array

    287. Find the Duplicate Number

    268. Missing Number

  • 相关阅读:
    Python大婶博客汇总
    DevOps之零停机部署
    DevOps之持续交付
    DevOps工具链
    DevOps的概念
    敏捷开发
    自动化运维
    tomcat优化
    java 集合专练
    java匿名内部类,多态,接口练习
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7669858.html
Copyright © 2011-2022 走看看