41. First Missing Positive
Given an unsorted integer array, find the first missing positive integer.For example,
Given return 3,
and return 2.
Your algorithm should run in O(n) time and uses constant space.
example [-1,-2, 1,3];
i ++;
i++ ;
i = 2nums = 1;nums -1] = nums exchange with nums ->
i++;
i=3 nums = 3 -> nums exchange with nums - > ;
out of loop
anther loopnums= 1 got, nums =-2 return i+1 -> 2
public class Solution {
public int firstMissingPositive(int[] nums) {
int i = 0 ;
while(i < nums.length){
if(nums == i + 1 || nums <= 0 || nums > nums.length) i++;
else if(nums != nums-1]) swap(nums, i, nums-1);
else i++;
}
i = 0;
while(i < nums.length && i+1 == nums) i++;
return i+1;
}
public void swap(int[] nums, int i, int j){
int temp = nums;
nums = nums;
nums = temp;
}
}
页:
[1]