41. First Missing Positive
Problem description:
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:1
2Input: [1,2,0]
Output: 3
Example 2:1
2Input: [3,4,-1,1]
Output: 2
Example 3:1
2Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
Solution:
The idea of this question is we can traverse the whole array once, putting every element in a slot.
So, how do we know where we should put this element?
Let’s check and observe the example.
- Input: [1,2,0]
- Zero and negative number does not count: The question is asking for missing positive number.
- we can put the number
nums[i]
in sloti-1
- Input: [3,4,-1,1]
[-1,4,3,1]
[-1,1,3,4]
Output: 2
- if we put the numbers into the slot that we observed earlier, we can get [-1,1,3,4]; however, if we stop here,
1
is not in the right place. Therefore, we need to keep swapping until thei
th element contains correct number or a zero/negative number.
- Input: [7,8,9,11,12]
Output: 1
- every element in the array exceed the size of array
1 | class Solution { |
time complexity: $O(n)$
space complexity: $O(1)$
reference:
https://goo.gl/Rq1yXX