最后一遍-L41-First Missing Positive
描述:
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is in the array but 2 is missing.
Example 3:
Input: nums = [7,8,9,11,12]
Output: 1
Explanation: The smallest positive integer 1 is missing.
Constraints:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
快慢指针的变化:Floyd Cycle
public class L41 {
public static void main(String[] args) {
System.out.println("Keep Moving !! ");
int value = firstMissingPositive(new int[]{1,2,0});
System.out.println(value);
value = firstMissingPositive(new int[]{3,4,-1,1});
System.out.println(value);
value = firstMissingPositive(new int[]{7,8,9,11,12});
System.out.println(value);
value = firstMissingPositive(new int[]{2,1});
System.out.println(value);
}
/**
* 发现最小的正数,关键在于想到这中方法
* */
public static int firstMissingPositive(int[] a) {
int i=0;
while(i < a.length){
if(a[i]< a.length && a[i] >0 && a[i] != i+1){
swap(a,a[i]-1,i);
continue;
}
i++;
}
i=0;
while(i < a.length && a[i] == i+1) i++;
return i+1;
}
private static void swap(int[] a, int i, int j) {
int tmp = a[j];
a[j] = a[i];
a[i] = tmp;
}
}