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.
这道题的最小数据是从<=0开始的,找乱序数组中第一个缺失的正整数。这样的题设条件,使得可以使用hashset来做,只需要i从1开始遍历,找第一个在hashset中不存在的数即可。空间复杂度会很高。
另一种方法是用A[]本身做hash,将i放置在i - 1的位置上。遍历数组,如果i不在i - 1上就将其与放在i - 1位置上的数交换。
Source1
public int firstMissingPositive(int[] A) {
HashSet<Integer> hs = new HashSet<Integer>();
for(int i = 0; i < A.length; i++){
if(A[i] > 0) hs.add(A[i]);
}
for(int i = 1; ; i++){
if(!hs.contains(i)) return i;
}
}
Test
public static void main(String[] args){
int[] A = {1,2,5,6,4};
System.out.println(new Solution().firstMissingPositive(A));
}
Source2
public int firstMissingPositive(int[] A) {
for(int i = 0; i < A.length; i++){
if(A[i] > 0 && A[i] <= A.length && A[i] != A[A[i] - 1]){
//由于最小数是<=0的,所以数组中>A.length的数不用考虑,也没地方放
//数字i应当等于放在i-1的位置上的值,比如数字3,应当放在2的位置上
int temp = A[A[i] - 1];
A[A[i] - 1] = A[i];
A[i] = temp;
i --; //交换完该位置上的数不一定是该位置上应有的数,所以重新判断
}
}
for(int i = 0; i < A.length; i++){
if(A[i] != i + 1)
return i + 1;
}
return A.length + 1;
}