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

146 lines
5.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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>进入。
#### [41. ](https://leetcode-cn.com/problems/first-missing-positive/)
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 Code:
```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];
}
}
}
```
Python3 Code:
```py
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
def swap(nums, a, b):
temp = nums[a]
nums[a] = nums[b]
nums[b] = temp
i = 0
while i < n:
num = nums[i]
#
if num <= 0 or num >= n or num == i + 1 or nums[num - 1] == num:
i += 1
#
else:
swap(nums, i, num - 1)
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
```