From 75e1bb2e7ba1c5334b30068882db8c27cf078982 Mon Sep 17 00:00:00 2001 From: Asterisk <44215173+casnz1601@users.noreply.github.com> Date: Thu, 21 Oct 2021 12:54:24 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200031.=E4=B8=8B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=8E=92=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增python代码: 抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用,故选择另一种算法暂且提供一种python思路 --- problems/0031.下一个排列.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 9efcb06a..470c354d 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -122,6 +122,33 @@ class Solution { ## Python ```python +class Solution: + ''' + 抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用。 + 故选择另一种算法暂且提供一种python思路 + ''' + def nextPermutation(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + length = len(nums) + for i in range(length-1, 0, -1): + if nums[i-1] < nums[i]: + for j in range(length-1, 0, -1): + if nums[j] > nums[i-1]: + nums[i-1], nums[j] = nums[j], nums[i-1] + break + self.reverse(nums, i, length-1) + break + else: + # 若正常结束循环,则对原数组直接翻转 + self.reverse(nums, 0, length-1) + + def reverse(self, nums: List[int], low: int, high: int) -> None: + while low < high: + nums[low], nums[high] = nums[high], nums[low] + low += 1 + high -= 1 ``` ## Go From 1598341473568669dae56e3c1e84bef56f090147 Mon Sep 17 00:00:00 2001 From: Asterisk <44215173+casnz1601@users.noreply.github.com> Date: Thu, 21 Oct 2021 12:58:03 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200031.=E4=B8=8B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=8E=92=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充python sorted()代码 --- problems/0031.下一个排列.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 470c354d..9999486e 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -120,7 +120,22 @@ class Solution { ``` ## Python - +>直接使用sorted()不符合题意 +```python +class Solution: + def nextPermutation(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + for i in range(len(nums)-1, -1, -1): + for j in range(len(nums)-1, i, -1): + if nums[j] > nums[i]: + nums[j], nums[i] = nums[i], nums[j] + nums[i+1:len(nums)] = sorted(nums[i+1:len(nums)]) + return + nums.sort() +``` +>另一种思路 ```python class Solution: '''