Skip to content

Commit 8206625

Browse files
refactor 31
1 parent 044ae59 commit 8206625

File tree

1 file changed

+36
-36
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+36
-36
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
11
package com.fishercoder.solutions;
22

33
public class _31 {
4-
public static class Solution1 {
5-
/**
6-
* Leetcode has a very good article to illustrate this problem and with animation:
7-
* https://leetcode.com/articles/next-permutation/
8-
* 1. if the array is already in decrementing order, then there's no next larger permutation possible.
9-
* 2. if not, start from the end of the array, find the first pair of numbers that break the decrementing order
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
12-
*/
4+
public static class Solution1 {
5+
/**
6+
* Leetcode has a very good article to illustrate this problem and with animation:
7+
* https://leetcode.com/articles/next-permutation/
8+
* 1. if the array is already in decrementing order, then there's no next larger permutation possible.
9+
* 2. if not, start from the end of the array, find the first pair of numbers that break the decrementing order
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
12+
*/
1313

14-
public void nextPermutation(int[] nums) {
15-
int i = nums.length - 2;
16-
while (i >= 0 && nums[i] >= nums[i + 1]) {
17-
i--;
18-
}
19-
if (i >= 0) {
20-
int j = nums.length - 1;
21-
while (j >= 0 && nums[i] >= nums[j]) {
22-
j--;
23-
}
14+
public void nextPermutation(int[] nums) {
15+
int i = nums.length - 2;
16+
while (i >= 0 && nums[i] >= nums[i + 1]) {
17+
i--;
18+
}
19+
if (i >= 0) {
20+
int j = nums.length - 1;
21+
while (j >= 0 && nums[i] >= nums[j]) {
22+
j--;
23+
}
2424

25-
swap(nums, i, j);
26-
}
25+
swap(nums, i, j);
26+
}
2727

28-
reverse(nums, i + 1);
29-
}
28+
reverse(nums, i + 1);
29+
}
3030

31-
private void reverse(int[] nums, int start) {
32-
int end = nums.length - 1;
33-
while (start <= end) {
34-
int tmp = nums[start];
35-
nums[start++] = nums[end];
36-
nums[end--] = tmp;
37-
}
38-
}
31+
private void reverse(int[] nums, int start) {
32+
int end = nums.length - 1;
33+
while (start <= end) {
34+
int tmp = nums[start];
35+
nums[start++] = nums[end];
36+
nums[end--] = tmp;
37+
}
38+
}
3939

40-
private void swap(int[] nums, int i, int j) {
41-
int tmp = nums[i];
42-
nums[i] = nums[j];
43-
nums[j] = tmp;
40+
private void swap(int[] nums, int i, int j) {
41+
int tmp = nums[i];
42+
nums[i] = nums[j];
43+
nums[j] = tmp;
44+
}
4445
}
45-
}
4646
}

0 commit comments

Comments
 (0)