mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0031.下一个排列.md
添加 0031.下一个排列Java版本的优化代码,时间复杂度为O(N),空间复杂度O(1)
This commit is contained in:
@ -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<j;i++,j--){
|
||||
int temp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Python
|
||||
>直接使用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
|
||||
|
||||
|
Reference in New Issue
Block a user