Skip to content

Commit 0bd6aa0

Browse files
update 31
1 parent ce35319 commit 0bd6aa0

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_31.java

+7-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@ public static class Solution1 {
88
* 1. if the array is already in decrementing order, then there's no next larger permutation possible.
99
* 2. if not, start from the end of the array, find the first pair of numbers that break the decrementing order
1010
* 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
1217
*/
1318

1419
public void nextPermutation(int[] nums) {
@@ -31,9 +36,7 @@ public void nextPermutation(int[] nums) {
3136
private void reverse(int[] nums, int start) {
3237
int end = nums.length - 1;
3338
while (start <= end) {
34-
int tmp = nums[start];
35-
nums[start++] = nums[end];
36-
nums[end--] = tmp;
39+
swap(nums, start++, end--);
3740
}
3841
}
3942

Diff for: src/test/java/com/fishercoder/_31Test.java

+14
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,18 @@ public void test3() {
3535
solution1.nextPermutation(nums);
3636
assertArrayEquals(new int[]{1, 2, 6, 1, 2, 3, 4}, nums);
3737
}
38+
39+
@Test
40+
public void test4() {
41+
nums = new int[]{1, 2, 5, 4, 3};
42+
solution1.nextPermutation(nums);
43+
assertArrayEquals(new int[]{1, 3, 2, 4, 5}, nums);
44+
}
45+
46+
@Test
47+
public void test5() {
48+
nums = new int[]{3, 2, 1};
49+
solution1.nextPermutation(nums);
50+
assertArrayEquals(new int[]{1, 2, 3}, nums);
51+
}
3852
}

0 commit comments

Comments
 (0)