zoukankan      html  css  js  c++  java
  • leetcode -- First Missing Positive

    Given an unsorted integer array, find the first missing positive integer.

    For example,
    Given [1,2,0] return 3,
    and [3,4,-1,1] return 2.

    Your algorithm should run in O(n) time and uses constant space.

    本题要求在O(n)时间内完成,并且使用O(1)空间

    O(n)时间则说明要使用hash来解本题,O(1)空间要求不能另开一个数组来进行hash,只能声明变量或者使用输入数组来进行

    这题是使用输入数组来进行hash

    本题的输入正整数范围为1<=input <= len; 核心思路是将输入放于相应的位置,如1应当放于i=0出(A[i]== i + 1)。

    key observation:first missing positive只可能是1,....n,n+1

    故我们将每一个数都放到相应的位置,然后遍历数组查看哪个位置的数不是相应的数即可找到missing positive

     1 public int firstMissingPositive(int[] A) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int len = A.length;
     5         for (int i = 0; i < len; i++) {
     6             //use a while to put the element to correct place
     7             while (A[i] > 0 && A[i] != i + 1 && A[i] <= len) {
     8                 if (A[i] == A[A[i] - 1])
     9                     break;
    10                 int tmp = A[i];
    11                 A[i] = A[A[i] - 1];
    12                 A[tmp - 1] = tmp;           // original A[A[i] - 1] = tmp;      error!!!
    13             }
    14 
    15         }
    16         int idx = 0;
    17         for (; idx < len; idx++) {
    18             if (A[idx] < 0 || A[idx] != idx + 1) {
    19                 return idx + 1;
    20             }
    21         }
    22 
    23         return idx + 1;
    24     }

    本题有所多tricky的地方:

    1. line 7 使用while循环来处理swap后的数,直到所有swap后的数都在正确的位置或者如line 8:A[i] == A[A[i] - 1]

    2. line 10~12进行swap时,A[i]的值会发生改变,因此在line12需使用A[tmp-1]来进行赋值  

    
    
  • 相关阅读:
    你真的知道async/await的好处嘛, 并且还会用好呢
    Python基本小程序
    猜数字小程序的实现
    Python第一周基本语句学习整理
    Python环境安装与配置
    作业
    Markdown的学习
    创建一个dynamics CRM workflow (四)
    Dynamics CRM 快速获取custom entity
    Dynamics email的subject标题出现 CRM:0000xxxx
  • 原文地址:https://www.cnblogs.com/feiling/p/3235977.html
Copyright © 2011-2022 走看看