0%

Leetcode041-firstMissingPositive

Description

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

Example

Example 1:

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

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

Example 3:
1
2
Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) return 1;

int i = 0;
// If the current value is in the range of (0,length) and it's not at its correct position,
// swap it to its correct position.
// Else just continue;
while (i < nums.length){
if (nums[i] == i + 1 || nums[i] <= 0 || nums[i] > nums.length || nums[i] == nums[nums[i] - 1]) i++;
else swap(nums, i, nums[i] - 1);
}
for (i = 0; i < nums.length; i++)
if (nums[i] != i + 1) break;
return i+1;
}

private void swap(int[] nums, int x, int y){
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}
}