题目
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3Example 2:
Input: [3,4,-1,1]
Output: 2Example 3:
Input: [7,8,9,11,12]
Output: 1- Note:
Your algorithm should run in O(n) time and uses constant extra space.
分析题目
- 本题让我们找缺失的首个正数
- 限定了O(n)的时间,所以一般的排序方法都不能用.限定了空间复杂度O(1),所以不能建立新的数组.那么我们只能覆盖原有数组,我们的思路是把1放在数组第一个位置nums[0],2放在第二个位置nums[1],即需要把nums[i]放在nums[nums[i] - 1]上,那么我们遍历整个数组,如果nums[i] != i + 1, 而nums[i]为整数且不大于n,另外nums[i]不等于nums[nums[i] - 1]的话,我们将两者位置调换,如果不满足上述条件直接跳过,最后我们再遍历一遍数组,如果对应位置上的数不正确则返回正确的数.
代码
Complexity - Time: O(n), Space: O(1)
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
int i = 0;
while (i < n) {
if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) {
swap(nums, i, nums[i] - 1); // 交换并且不增加i的值,直到条件不满足
} else {
i++;
}
}
for (int j = 0; j < n; j++) {
if (nums[j] != j + 1) {
return j + 1;
}
}
return n + 1;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}