Files
LeetCode/普通数组/5. 缺失的第一个正数.md
2025-10-01 20:39:22 +08:00

60 lines
1.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 缺失的第一个正数
## 题目
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
示例 1:
输入:nums = [1,2,0]
输出:3
解释:范围 [1,2] 中的数字都在数组中。
示例 2:
输入:nums = [3,4,-1,1]
输出:2
解释:1 在数组中,但 2 没有。
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
解释:最小的正数 1 没有出现。
提示:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
## 思路
- 将数组当做 hashMap,下标当做 key
## 代码
```java
class Solution {
public int firstMissingPositive(int[] nums) {
// Init: "HashMap"
// Traverse: Add nums
for (int i = 0; i < nums.length; i++) {
while (nums[i] >=1 && nums[i] <= nums.length && nums[nums[i] - 1] != nums[i]) {
// swap: i <=> nums[i] - 1
int tmp = nums[i];
nums[i] = nums[tmp - 1];
nums[tmp - 1] = tmp;
}
}
// Traverse: Judge
for (int i = 0; i< nums.length; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return nums.length + 1;
}
}
```