题目:
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.
解决:
正负来来记录,值映射到位置。
public class Solution {
public int firstMissingPositive(int[] A) {
for (int i=0; i < A.length; i++){
if (A[i]<=0) A[i]=(A.length+2);//把0与负mo去
}
for (int i=0;i<A.length;i++){
if (Math.abs(A[i])<A.length+1){//把0与负mo去
int cur = Math.abs(A[i])-1;
A[cur] = -Math.abs(A[cur]);//用正负来记录,值映射到位置
}
}
for (int i=0; i < A.length; i++)
if (A[i]>0) return i+1;//没有映射到的位置就是缺的数
return A.length+1;
}
}