Skip to content

Commit 85b272f

Browse files
committed
Create 41.缺失的第一个正数(困难).md
1 parent f5e8818 commit 85b272f

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
```text
2+
题目: 给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数
3+
示例1:
4+
输入: [1,2,0]
5+
输出: 3
6+
示例2:
7+
输入: [3,4,-1,1]
8+
输出: 2
9+
示例3:
10+
输入: [7,8,9,11,12]
11+
输出: 1
12+
提示: 你的算法的时间复杂度应为O(n),并且只能使用常数级别的额外空间
13+
1.双指针:
14+
[1]思路:
15+
(1)由于未排序直接寻找很难,因此首先是排序,只要时间复杂度小于或等于O(n)即可;
16+
(2)考虑数组长度和边界条件,当数组长度等于0或数组第一个元素大于1时,直接返回1;
17+
(3)使用双指针,定义一个指针保存前一个遍历到的元素,如果当前元素和前一个元素差1,则说明是连续递增的;
18+
(4)考虑到题目要求是没有出现的最小的正整数,所以遍历时直接过滤掉小于等于0的元素;
19+
(5)考虑到数组中可能存在相同的元素,则当两指针对应元素相同则跳过;
20+
[2]实现:
21+
class Solution {
22+
public int firstMissingPositive(int[] nums) {
23+
Arrays.sort(nums);
24+
if (nums.length==0 || nums[0] > 1) {
25+
return 1;
26+
}
27+
// 双指针pre和i
28+
int pre = 0;
29+
for (int i = 0; i < nums.length; i++) {
30+
// 过滤掉小于等于0的元素和跳过重复的元素
31+
if (nums[i] <= 0 || nums[i]==pre) {
32+
continue;
33+
}
34+
if (nums[i] - pre == 1) {
35+
pre = nums[i];
36+
} else {
37+
return pre+1;
38+
}
39+
}
40+
return pre+1;
41+
}
42+
}
43+
[3]复杂度分析:
44+
(1)时间复杂度: O(N),N为数组长度
45+
(2)空间复杂度: O(1)
46+
```

0 commit comments

Comments
 (0)