forked from yuanx/leetcode
-
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) · 824 Bytes
/
NextPermutation.java
File metadata and controls
55 lines (50 loc) · 824 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
44
45
46
47
48
49
50
51
52
53
54
55
public class Solution {
public void nextPermutation(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
int len = num.length;
if(len<=1) return;
int i= len-1;
while(i>0){
if(num[i]<=num[i-1])
i--;
else
break;
}
if(i==0){
reverse(num);
return;
}
int p = i-1;
while(i<len){
if(num[i]>num[p])
i++;
else
break;
}
i--;
swap(num, p, i);
p++;
int q = len-1;
while(q>p){
swap(num,p,q);
p++;
q--;
}
}
public void swap(int[] num, int i, int j){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
public void reverse(int[] num){
if(num.length==1) return;
int p = 0;
int q = num.length-1;
while(q>p){
swap(num,p,q);
p++;
q--;
}
}
}