41. 缺失的第一个正数
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-missing-positive
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private void swap(int[] nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
public int firstMissingPositive(int[] nums) {
int index = 0, right = nums.length - 1;
while (index <= right) {
if (nums[index] == index + 1) {
index++;
} else if (nums[index] < index + 1 || nums[index] > right + 1) {
swap(nums, index, right--);
} else {
if (nums[nums[index] - 1] == nums[index]) {
swap(nums, index, right--);
} else {
swap(nums, index, nums[index] - 1);
}
}
}
return index + 1;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号