File tree 1 file changed +22
-25
lines changed
1 file changed +22
-25
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public void nextPermutation (int [] nums ) {
3
- boolean flag = true ;
4
- int right = nums .length - 1 ;
5
- int start = right ;
6
- while (start >= 1 ) {
7
- if (nums [start ] > nums [start - 1 ]) {
8
- int idx = right ;
9
- while (nums [idx ] <= nums [start - 1 ]) {
10
- idx --;
11
- }
12
- int temp = nums [start - 1 ];
13
- nums [start - 1 ] = nums [idx ];
14
- nums [idx ] = temp ;
15
- flag = false ;
16
- break ;
17
- }
18
- start --;
19
- }
20
- if (flag ) {
21
- Arrays .sort (nums );
3
+ if (nums .length <= 1 ) {
22
4
return ;
23
5
}
24
- while (start < right ) {
25
- int temp = nums [start ];
26
- nums [start ] = nums [right ];
27
- nums [right ] = temp ;
28
- start ++;
29
- right --;
6
+ int idx = nums .length - 2 ;
7
+ while (idx >= 0 && nums [idx ] >= nums [idx + 1 ]) {
8
+ idx --;
9
+ }
10
+ if (idx >= 0 ) {
11
+ int endIdx = nums .length - 1 ;
12
+ while (nums [endIdx ] <= nums [idx ]) {
13
+ endIdx --;
14
+ }
15
+ swap (nums , idx , endIdx );
16
+ }
17
+ int startIdx = idx + 1 ;
18
+ int endIdx = nums .length - 1 ;
19
+ while (startIdx < endIdx ) {
20
+ swap (nums , startIdx ++, endIdx --);
30
21
}
31
22
}
23
+
24
+ private void swap (int [] nums , int idxOne , int idxTwo ) {
25
+ int temp = nums [idxOne ];
26
+ nums [idxOne ] = nums [idxTwo ];
27
+ nums [idxTwo ] = temp ;
28
+ }
32
29
}
You can’t perform that action at this time.
0 commit comments