-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path31. Next Permutation
More file actions
52 lines (38 loc) · 884 Bytes
/
31. Next Permutation
File metadata and controls
52 lines (38 loc) · 884 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
Runtime 0 ms
Beats 100%
Memory 41.6 MB
Beats 98.42%
class Solution {
public static void reverse(int a[],int i){
int j=i,k=a.length-1;
while(j<k){
swap(a,j,k);
j++;k--;
}
}
public static void swap(int a[],int i,int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public void nextPermutation(int[] nums) {
int index=-1,n=nums.length,i=0;
for( i=n-2;i>=0;i--){
if(nums[i]<nums[i+1]){
index=i;
break;
}
}
if(index == -1){
reverse(nums,0);
}else{
for( i=n-1;i>=index;i--){
if(nums[i]>nums[index]){
swap(nums,i,index);
break;
}
}
reverse(nums,index+1);
}
}
}