First Missing Positive Integer

Question

Given an unsorted integer array, find the smallest missing positive integer.

Example

1
2
3
4
5
Input: [1,2,0]
Output: 3

Input: [3,4,-1,1]
Output: 2

Solution

Actually, this approach is quite tricky to me. We have to maintain the sequence like index0 -> 1, index1 -> 2, etc, when we see the element didn’t meet the requirement we have to swap until we cannot move or meet the requirement. nums[i] should be nums[i] - 1(index) position.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// time:O(n)
// space:O(1)
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) return 1;
for (int i = 0; i < nums.length; i++) {
while (nums[i] - 1 >= 0 && nums[i] - 1 < nums.length
&& nums[i] != nums[nums[i] - 1]) {
exch(nums, nums[i] - 1, i);
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) return i + 1;
}
return nums.length + 1;
}

public void exch(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}