algorithm-base/animation-simulation/数组篇/leetcode41缺失的第一个正数.md

118 lines
4.8 KiB
Java
Raw Normal View History

2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:48:03 +00:00
#### [41. ](https://leetcode-cn.com/problems/first-missing-positive/)
2021-03-19 11:04:42 +00:00
1:
> : [1,2,0]
> : 3
2:
> : [3,4,-1,1]
> : 2
3:
> : [7,8,9,11,12]
> : 1
###
使
![_20210109135536](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210109135536.41h4amio2me0.png)
newnum[i] != i 2 5 5
1 1
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/缺失的第一个正数.1it1cow5aa8w.gif)
```java
class Solution {
public int firstMissingPositive(int[] nums) {
if (nums.length == 0) {
return 1;
}
//因为是返回第一个正整数,不包括 0所以需要长度加1细节1
int[] res = new int[nums.length + 1];
//将数组元素添加到辅助数组中
for (int x : nums) {
if (x > 0 && x < res.length) {
res[x] = x;
}
}
//遍历查找,发现不一样时直接返回
for (int i = 1; i < res.length; i++) {
if (res[i] != i) {
return i;
}
}
//缺少最后一个,例如 123此时缺少 4 细节2
return res.length;
}
}
```
使使 nums 使
绿
![1](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/置换1.4j4pcz56ml40.png)
![2](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/置换2.5rawbyws7h40.png)
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/原地置换.52wi0yoiu3o0.gif)
```java
class Solution {
public int firstMissingPositive(int[] nums) {
int len = nums.length;
if (len == 0) {
return 1;
}
for (int i = 0; i < len; ++i) {
//需要考虑指针移动情况大于0小于len+1不等与i+1两个交换的数相等时防止死循环
while (nums[i] > 0 && nums[i] < len + 1 && nums[i] != i+1 && nums[i] != nums[nums[i]-1]) {
swap(nums,i,nums[i] - 1);
}
}
//遍历寻找缺失的正整数
for (int i = 0; i < len; ++i) {
if(nums[i] != i+1) {
return i+1;
}
}
return len + 1;
}
//交换
public void swap(int[] nums, int i, int j) {
if (i != j) {
nums[i] ^= nums[j];
nums[j] ^= nums[i];
nums[i] ^= nums[j];
}
}
}
```