Problem
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Note:
Your algorithm should run in O(n) time and uses constant extra space.
Explanation 1
-
If the input array length is 3, then the result can be 4 at maximum. For example:
1
2
3
4input = [1, 2, 3], result == 4. input = [1, 5, 3], result < 4. input = [3, 3, 3], result < 4. input = [-1, 3, 2], result < 4.
-
We can create a boolean array with length same as the input array length. Then loop through each number, if the number
num
is not positive or the number is greater than length, we ignore it. Else, we put the boolean array’s indexnum-1
totrue
. Finally, we loop through the boolean array and find out the firstfalse
index and plus one to it and return as the result. For example1
2
3
4
5
6
7
8
9
10input = [1, 5, 3] boolean = [false, false, false] iterate to 1: boolean = [true, false, false] iterate to 5: boolean = [true, false, false] iterate to 3: boolean = [true, false, true] return 2 as the result.
-
If all elements in the boolean array are true, then we return array length plus one. For example
input=[1, 2, 3]
, booleanArr =[true, true, true]
. We return 4.
Solution 1
1 |
|
Explanation 2
-
We loop through the array, if the number is not positive, we change it to the maximum of integer.
-
Second loop, if the current element’s value is greater than array length, we ignore it. Else, we use the current element’s value minus one as index, then in the array, change that index’s element to negative.
-
Third loop, if the current element is positive, then we return its index plus one as the result. If finish looping and no element is positive, then we return the length plus one as result.
1
2
3
4
5
6
7
8
9
10
11
12
13input: [2, -1, 3, 1, 0, -5, 10] first loop: [2, max, 3, 1, max, max, 10] second loop: [2, -max, 3, 1, max, max, 10] [2, -max, -3, 1, max, max, 10] [-2, -max, -3, 1, max, max, 10] third loop: 1 at index 3 is positive, return 3+1=4 as result.
Solution 2
1 |
|
Explanation 3
-
We can also use Cyclic Sort’s swapping method to solve this problem.
-
First start from the first number
nums[i]
in the array. Ifnums[i]
is within the range between 1 tonums.length
, and its valuenums[i]
is not equal to its corresponding indexnums[i]-1
’s value, in other words, ifnums[i] != nums[nums[i]-1]
, then we swap these two elements. Else, we increasei
. Repeat whilei
is less thannums.length
. -
Loop from the first number to the last. If the current index is not equals to current value’s corresponding index, in other words, if
nums[i]-1 != i
, that means we are missing the current index’s corresponding value which isi+1
.
Solution 3
1 |
|