First Missing Positive
Problem: First Missing Positive
We can mark numbers at position with appearing indexes as negative. For original negative numbers, we modify them as a number bigger then length of array at first. If there remains positive numbers, the index of that position is missing.
Code in Python:
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
for i in xrange(n):
if nums[i] <= 0: nums[i] = len(nums)+1
for i in xrange(n):
if abs(nums[i]) <= n: nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1])
for i in xrange(n):
if nums[i] > 0: return i+1
return n+1
Code in Java:
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums.length == 0 || nums == null) return 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= 0) nums[i] = nums.length+1;
}
for (int i = 0; i < nums.length; i++) {
if (Math.abs(nums[i]) <= nums.length) nums[Math.abs(nums[i])-1] = -Math.abs(nums[Math.abs(nums[i])-1]);
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) return i+1;
}
return nums.length+1;
}
}