-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
43 lines (37 loc) · 983 Bytes
/
NextPermutation.java
File metadata and controls
43 lines (37 loc) · 983 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
36
37
38
39
40
41
42
43
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
if(n > 0){
// Find suffix length
int r = n-1;
while(r > 0){
if(nums[r-1] >= nums[r]){
r--;
} else {
break;
}
}
if(r > 0){
int pivot = r-1;
int q = r;
for(int i=r; i < n; i++){
if(nums[i] <= nums[q] && nums[i] > nums[pivot]) q = i;
}
swap(nums, pivot, q);
}
reverse(nums, r, n-1);
}
}
public void reverse(int[] nums, int start, int end){
while(start < end){
swap(nums, start, end);
start++;
end--;
}
}
public void swap(int[] nums, int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}