mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #1556 from Invalided/master
添加 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
|
## Python
|
||||||
>直接使用sorted()不符合题意
|
>直接使用sorted()不符合题意
|
||||||
@ -164,7 +206,7 @@ class Solution:
|
|||||||
high -= 1
|
high -= 1
|
||||||
```
|
```
|
||||||
>上一版本简化版
|
>上一版本简化版
|
||||||
'''python
|
```python
|
||||||
class Solution(object):
|
class Solution(object):
|
||||||
def nextPermutation(self, nums: List[int]) -> None:
|
def nextPermutation(self, nums: List[int]) -> None:
|
||||||
n = len(nums)
|
n = len(nums)
|
||||||
@ -185,7 +227,7 @@ class Solution(object):
|
|||||||
end -= 1
|
end -= 1
|
||||||
|
|
||||||
return nums
|
return nums
|
||||||
'''
|
```
|
||||||
|
|
||||||
## Go
|
## Go
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user