题目:
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.
方法:
遍历,如果当前index的对应值在[1, len-1]范围内,检查 1. index的对应值减一是否是index, 2. 以对应值为index的对应值是否为A[index];如果两个有一个不符合,那么交换,并且index返回前一位。
检查遍历数组,发现A[index]-1 != index,返回index+1;遍历结束程序还未结束,则返回len+1
代码:
public class Solution {
public int firstMissingPositive(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A==null || A.length==0) return 1;
for(int i=0; i<A.length; i++){
if(A[i]>0 && A[i]<A.length){
if(A[i]-1!=i && A[A[i]-1]!=A[i]){
int tmp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = tmp;
i--;
}
}
}
for(int i=0; i<A.length; i++)
if(A[i]-1 != i)
return i+1;
return A.length + 1;
}
}
总结:
1. index对应值,和以index的值为index的对应值,两者互换,必定有一个正确归位
2. 归位步骤完成,index返回上一层的原因在于,如果是前面的值归位到后面,那么原本后面的值无法被遍历,因此,加上这一步保证全遍历
相当精巧的一道题,很牛的算法,O(n),赞一个。