-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31.下一个排列.java
40 lines (36 loc) · 944 Bytes
/
31.下一个排列.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
* @lc app=leetcode.cn id=31 lang=java
*
* [31] 下一个排列
*/
// @lc code=start
class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 1;
while (i > 0 && nums[i - 1] >= nums[i]) {
i--;
}
if (i > 0) {
// swap (i - 1) and item in [i,] that greater than it
for (int j = nums.length - 1; j >= i; j--) {
if (nums[j] > nums[i - 1]) {
int tmp = nums[j];
nums[j] = nums[i - 1];
nums[i - 1] = tmp;
break;
}
}
}
// reverse [i,]
int phead = i;
int ptail = nums.length - 1;
while (phead < ptail) {
int tmp = nums[phead];
nums[phead] = nums[ptail];
nums[ptail] = tmp;
phead++;
ptail--;
}
}
}
// @lc code=end