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]来进行赋值  


posted @ 2013-08-04 09:57  feiling  阅读(210)  评论(0编辑  收藏  举报