Skip to content

Commit 2e003ab

Browse files
authored
feat(ml):leetcode41缺失的第一个正数 添加 Python3 代码
1 parent 107732a commit 2e003ab

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ class Solution {
8383

8484
题目代码:
8585

86+
Java Code:
87+
8688
```java
8789
class Solution {
8890
public int firstMissingPositive(int[] nums) {
@@ -115,3 +117,29 @@ class Solution {
115117
}
116118
```
117119

120+
Python3 Code:
121+
122+
```py
123+
class Solution:
124+
def firstMissingPositive(self, nums: List[int]) -> int:
125+
n = len(nums)
126+
127+
def swap(nums, a, b):
128+
temp = nums[a]
129+
nums[a] = nums[b]
130+
nums[b] = temp
131+
i = 0
132+
while i < n:
133+
num = nums[i]
134+
# 已经就位
135+
if num <= 0 or num >= n or num == i + 1 or nums[num - 1] == num:
136+
i += 1
137+
# 可以交换
138+
else:
139+
swap(nums, i, num - 1)
140+
for i in range(n):
141+
if nums[i] != i + 1:
142+
return i + 1
143+
return n + 1
144+
```
145+

0 commit comments

Comments
 (0)