From 2e003abb47a2339ae0edb9f53f8696c96ebc278c Mon Sep 17 00:00:00 2001 From: lucifer Date: Mon, 26 Apr 2021 14:50:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(ml):leetcode41=E7=BC=BA=E5=A4=B1=E7=9A=84?= =?UTF-8?q?=E7=AC=AC=E4=B8=80=E4=B8=AA=E6=AD=A3=E6=95=B0=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=20Python3=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../数组篇/leetcode41缺失的第一个正数.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/animation-simulation/数组篇/leetcode41缺失的第一个正数.md b/animation-simulation/数组篇/leetcode41缺失的第一个正数.md index 2dbe489..6c46f4d 100644 --- a/animation-simulation/数组篇/leetcode41缺失的第一个正数.md +++ b/animation-simulation/数组篇/leetcode41缺失的第一个正数.md @@ -83,6 +83,8 @@ class Solution { 题目代码: +Java Code: + ```java class Solution { public int firstMissingPositive(int[] nums) { @@ -115,3 +117,29 @@ class Solution { } ``` +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 +``` +