Leetcode 41. First Missing Positive
算法:
- Check if 1 is present in the array. If not, you’re done and 1 is the answer. If nums = [1], the answer is 2. Replace negative numbers, zeros, and numbers larger than n by 1s. 检查1是否存在,不存在返回1。如果1存在,且数组只有一个元素,则返回2。把所有0,负数,大于数组size的数设置为1。
- Walk along the array. Change the sign of a-th element if you meet number a. Be careful with duplicates : do sign change only once. Use index 0 to save an information about presence of number n since index n is not available. 如果遇到1,就把数组下标为1的元素设置为负数。 如果遇到2,就把数组下标为2的元素设置为负数。以此类推。
- Walk again along the array. Return the index of the first positive element. 返回第一个数组里正数的下标。
- If nums[0] > 0 return n. 下标为0的元素大于0,例如:返回n. [1,2,3,1] -> 返回4
- If on the previous step you didn’t find the positive element in nums, that means that the answer is n + 1. 如果所有元素都大于0,返回n+1。
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
// Base case.
int contains = 0;
for (int i = 0; i < n; i++)
if (nums[i] == 1) {
contains++;
break;
}
if (contains == 0)
return 1;
// nums = [1]
if (n == 1)
return 2;
// Replace negative numbers, zeros,
// and numbers larger than n by 1s.
// After this convertion nums will contain
// only positive numbers.
for (int i = 0; i < n; i++)
if ((nums[i] <= 0) || (nums[i] > n))
nums[i] = 1;
// Use index as a hash key and number sign as a presence detector.
// For example, if nums[1] is negative that means that number `1`
// is present in the array.
// If nums[2] is positive - number 2 is missing.
for (int i = 0; i < n; i++) {
int a = Math.abs(nums[i]);
// If you meet number a in the array - change the sign of a-th element.
// Be careful with duplicates : do it only once.
if (a == n)
nums[0] = - Math.abs(nums[0]);
else
nums[a] = - Math.abs(nums[a]);
}
// Now the index of the first positive number
// is equal to first missing positive.
for (int i = 1; i < n; i++) {
if (nums[i] > 0)
return i;
}
if (nums[0] > 0)
return n;
return n + 1;
}
}