Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
return3
,
and[3,4,-1,1]
return2
.Your algorithm should run in O(n) time and uses constant space.
将A[i] 交换到 A[A[i] - 1]中,需要注意临界条件。PS:直接hash太浪费空间。
public int firstMissingPositive(int[] A) { int len = A.length; for (int i = 0; i < len; ) { if (A[i] > 0) { if (A[i] < len && A[i] != i + 1 && A[i] != A[A[i] - 1]) { int tempOne = A[i]; int tempTwo = A[A[i] - 1]; A[i] = tempTwo; A[tempOne - 1] = tempOne; } else { i++; } } else { i++; } } for (int i = 0; i < len; i++) { if (A[i] != i + 1) { return i + 1; } } return len + 1; }
First Missing Positive,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010378705/article/details/34956253