// 5.7
// 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 int firstMissingPositive(int[] nums) {
int idx = 0;
while (idx < nums.length) {
if (nums[idx] == idx + 1 || nums[idx] <= 0 || nums[idx] > nums.length) {
idx++;
} else {
if (nums[idx] == nums[nums[idx] - 1]) {
idx++;
} else {
swip(nums, idx, nums[idx] - 1);
}
}
}
idx = 0;
while (idx < nums.length && nums[idx] == idx + 1) {
idx++;
}
return idx + 1;
}
void swip(int[] ary,int x,int y) {
int temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
网友评论