-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNext Permutation
51 lines (49 loc) · 1.01 KB
/
Next Permutation
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
import java.util.* ;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class Solution
{
public static ArrayList<Integer> nextPermutation(ArrayList<Integer> permutation)
{
// Write your code here.
int k=permutation.size();
int nums[]=new int[k];
for(int i=0;i<k;i++)
{
nums[i]=permutation.get(i);
}
int i=nums.length-2;
int j=0;
while(i>=0 && nums[i]>=nums[i+1])
i--;
if(i>=0)
{
j=nums.length-1;
while(nums[j]<=nums[i])
j--;
swap(nums,i,j);
}
reverse(nums,i+1,nums.length-1);
for(int l=0;l<k;l++)
{
permutation.set(l,nums[l]);
}
return permutation;
}
static void swap(int nums[],int i,int j)
{
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
static void reverse(int nums[],int i,int j)
{
while(i<j)
{
swap(nums,i,j);
i++;
j--;
}
}
}