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