Skip to content

Commit 2edc43e

Browse files
committed
Added task 31.
1 parent 1f3dd8b commit 2edc43e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package s0031.next.permutation;
2+
3+
public class Solution {
4+
public void nextPermutation(int[] nums) {
5+
if (nums == null || nums.length <= 1) return;
6+
7+
int i = nums.length - 2;
8+
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
9+
10+
if (i >= 0) {
11+
int j = nums.length - 1;
12+
while (nums[j] <= nums[i]) j--;
13+
swap(nums, i, j);
14+
}
15+
reverse(nums, i + 1, nums.length - 1);
16+
}
17+
18+
public void swap(int[] nums, int i, int j) {
19+
int temp = nums[i];
20+
nums[i] = nums[j];
21+
nums[j] = temp;
22+
}
23+
24+
public void reverse(int[] nums, int i, int j) {
25+
while (i < j) swap(nums, i++, j--);
26+
}
27+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package s0031.next.permutation;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.Test;
7+
8+
public class SolutionTest {
9+
@Test
10+
public void nextPermutation() {
11+
int[] array = new int[] {1, 2, 3};
12+
new Solution().nextPermutation(array);
13+
assertThat(java.util.Arrays.toString(array), equalTo("[1, 3, 2]"));
14+
}
15+
}

0 commit comments

Comments
 (0)