From 1bfd42e702b997caf5563b1823be4067cd6ad0a6 Mon Sep 17 00:00:00 2001 From: Invalided <39646604+Invalided@users.noreply.github.com> Date: Mon, 1 Aug 2022 12:31:24 +0800 Subject: [PATCH] =?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 添加 0031.下一个排列Java版本的优化代码,时间复杂度为O(N),空间复杂度O(1) --- problems/0031.下一个排列.md | 46 ++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 1a3641b0..ada9deba 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -116,6 +116,48 @@ class Solution { } } ``` +> 优化时间复杂度为O(N),空间复杂度为O(1) +```Java +class Solution { + public void nextPermutation(int[] nums) { + // 1.从后向前获取逆序区域的前一位 + int index = findIndex(nums); + // 判断数组是否处于最小组合状态 + if(index != 0){ + // 2.交换逆序区域刚好大于它的最小数字 + exchange(nums,index); + } + // 3.把原来的逆序区转为顺序 + reverse(nums,index); + } + + public static int findIndex(int [] nums){ + for(int i = nums.length-1;i>0;i--){ + if(nums[i]>nums[i-1]){ + return i; + } + } + return 0; + } + public static void exchange(int [] nums, int index){ + int head = nums[index-1]; + for(int i = nums.length-1;i>0;i--){ + if(head < nums[i]){ + nums[index-1] = nums[i]; + nums[i] = head; + break; + } + } + } + public static void reverse(int [] nums, int index){ + for(int i = index,j = nums.length-1;i直接使用sorted()不符合题意 @@ -164,7 +206,7 @@ class Solution: high -= 1 ``` >上一版本简化版 -'''python +```python class Solution(object): def nextPermutation(self, nums: List[int]) -> None: n = len(nums) @@ -185,7 +227,7 @@ class Solution(object): end -= 1 return nums -''' +``` ## Go