-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnext_permutations.java
45 lines (43 loc) · 1.08 KB
/
next_permutations.java
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
class Solution {
public void nextPermutation(int[] nums) {
int ind1=-1;
int ind2=-1;
// step 1 find breaking point
for(int i=nums.length-2;i>=0;i--){
if(nums[i]<nums[i+1]){
ind1=i;
break;
}
}
// if there is no breaking point
if(ind1==-1){
reverse(nums,0);
}
else{
// step 2 find next greater element and swap with ind2
for(int i=nums.length-1;i>=0;i--){
if(nums[i]>nums[ind1]){
ind2=i;
break;
}
}
swap(nums,ind1,ind2);
// step 3 reverse the rest right half
reverse(nums,ind1+1);
}
}
void swap(int[] nums,int i,int j){
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
void reverse(int[] nums,int start){
int i=start;
int j=nums.length-1;
while(i<j){
swap(nums,i,j);
i++;
j--;
}
}
}