LeetCode 41. First Missing Positive
Question
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:
1 | Input: nums = [1,2,0] |
Example 2:
1 | Input: nums = [3,4,-1,1] |
Example 3:
1 | Input: nums = [7,8,9,11,12] |
Constraints:
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
Source: https://leetcode.com/problems/first-missing-positive/
Solution
We try to put every positive number n
on the position n-1
. Then we traverse the array to find the first number that num[i] != i + 1
, so that we get the first missing positive number. Note that there may be duplicate values that fit in the same position. We should skip the rest of them to avoid endless loop.
1 | private void swap(int[] nums, int i, int j) { |
LeetCode 41. First Missing Positive
http://yenotes.org/2022/03/09/LeetCode-41-First-Missing-Positive/