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) {
if(A==null || A.length==0) {
return 1;
}
for(int i=0;i<A.length;i++) {
if(A[i]>0 && A[i]<A.length && A[i]!=i+1 && A[A[i]-1]!=A[i]) {
int temp = A[i];
A[i] = A[temp-1];
A[temp-1] = temp;
i--;
}
}
for(int i=0;i<A.length;i++) {
if(i!=A[i]-1) {
return i+1;
}
}
return A.length+1;
}
}
====================
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) {
return 1;
}
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (n - 1 < nums.length && n - 1 >= 0 && nums[n - 1] != n) {
nums[i] = nums[n - 1];
nums[n - 1] = n;
i--;
}
}
for (int i = 0; i < nums.length; i++) {
if (i + 1 != nums[i]) {
return i + 1;
}
}
return nums.length + 1;
}
}
没有评论:
发表评论