@@ -8,7 +8,12 @@ public static class Solution1 {
8
8
* 1. if the array is already in decrementing order, then there's no next larger permutation possible.
9
9
* 2. if not, start from the end of the array, find the first pair of numbers that break the decrementing order
10
10
* 3. then from that index going to the right again, find the element that is closest bigger than this number, swap them
11
- * 4. reverse the right half of this array after this index
11
+ * 4. reverse the right half of this array after this index to make it sorted increasingly so that it's the next permutation
12
+ * <p>
13
+ * Use this nums as an example: 1,2,5,4,3
14
+ * 1. we first found such an adjacent pair: 2 and 5 that breaks the decrementing order;
15
+ * 2. then starting from the right side again, we find a number that's bigger than 2, so that is 3, swap them, the array becomes: 1,3,5,4,2
16
+ * 3. reverse this sub-array: 5,4,2 since they are guaranteed to be decreasing order, so reversing them will give us the next permutation: 1,3,2,4,5
12
17
*/
13
18
14
19
public void nextPermutation (int [] nums ) {
@@ -31,9 +36,7 @@ public void nextPermutation(int[] nums) {
31
36
private void reverse (int [] nums , int start ) {
32
37
int end = nums .length - 1 ;
33
38
while (start <= end ) {
34
- int tmp = nums [start ];
35
- nums [start ++] = nums [end ];
36
- nums [end --] = tmp ;
39
+ swap (nums , start ++, end --);
37
40
}
38
41
}
39
42
0 commit comments