From 2f31c2bee24b744316a9967c7762e2c14943d122 Mon Sep 17 00:00:00 2001 From: Wonder Date: Wed, 1 Oct 2025 20:39:22 +0800 Subject: [PATCH] =?UTF-8?q?=20=F0=9F=94=84Update:=20=E7=BC=BA=E5=A4=B1?= =?UTF-8?q?=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E6=AD=A3=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 普通数组/5. 缺失的第一个正数.md | 60 +++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 普通数组/5. 缺失的第一个正数.md diff --git a/普通数组/5. 缺失的第一个正数.md b/普通数组/5. 缺失的第一个正数.md new file mode 100644 index 0000000..de0eef6 --- /dev/null +++ b/普通数组/5. 缺失的第一个正数.md @@ -0,0 +1,60 @@ +# 缺失的第一个正数 + +## 题目 + +给你一个未排序的整数数组 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; + } +} +``` \ No newline at end of file