-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
55 lines (50 loc) · 1.1 KB
/
NextPermutation.java
File metadata and controls
55 lines (50 loc) · 1.1 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
package nextPermutation;
public class NextPermutation {
public void nextPermutation(int[] nums) {
int post = -1;
// for(int i = 1; i < nums.length; i++){
// if(nums[i] > nums[i-1]){
// post = i;
// }
// }
for(int i = nums.length-1; i>0; i--){
if(nums[i] >= nums[i-1]){
post = i;
break;
}
}
if(post == -1){
post = 0;
}
else{
int point = -1;
for(int j = post; j < nums.length; j++){
if(nums[j] > nums[post-1]){
point = j;
}
}
change(nums, post-1, point);
}
ArrayRotateTwo(nums, post);
}
public void change(int[] nums, int x, int y){
int t = 0;
t = nums[x];
nums[x] = nums[y];
nums[y] = t;
}
public void ArrayRotateTwo(int[] arr, int begin){
for(int x = begin, y = arr.length -1 ; x < y; x++, y--){
change(arr, x, y);
}
}
public static void main(String[] args){
int[] nums = new int[]{1,3,5,4,2};
NextPermutation t = new NextPermutation();
t.nextPermutation(nums);
//t.change(nums, 0, 1);
for (int i : nums) {
System.out.print(i+" ");
}
}
}