-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
35 lines (30 loc) · 836 Bytes
/
Copy pathSolution.java
File metadata and controls
35 lines (30 loc) · 836 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public void nextPermutation(int[] nums) {
// find the number that needs to replaced.
int n = nums.length;
int i = n - 2;
while (i >= 0 && nums[i + 1] <= nums[i]) {
i--;
}
if (i >= 0) {
int j = n - 1;
// find the first number smaller than the current number.
while (nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
private static void reverse(int[] nums, int begin) {
int i = begin, j = nums.length - 1;
while (i < j) {
swap(nums, i++, j--);
}
}
private static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}