forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextpermutation.java
More file actions
executable file
·45 lines (42 loc) · 1.04 KB
/
nextpermutation.java
File metadata and controls
executable file
·45 lines (42 loc) · 1.04 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
public class Solution {
public void reverse(int[] num, int left, int right){
while(left<right){
int tmp = num[left];
num[left] = num[right];
num[right] = tmp;
left++;
right--;
}
}
public void nextPermutation(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
int last = num.length-1;
while(true){
if(last==0){
break;
}
if(num[last]<=num[last-1]){
last--;
}else{
break;
}
}
if(last==0){
reverse(num,0,num.length-1);
return;
}
int start = last-1;
int i;
for(i=last;i<num.length;i++){
if(num[i]<=num[start]){
break;
}
}
int tmp = num[start];
num[start] = num[i-1];
num[i-1] = tmp;
reverse(num,last,num.length-1);
return;
}
}