forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path31 Next Permutation
More file actions
46 lines (34 loc) Ā· 1.22 KB
/
31 Next Permutation
File metadata and controls
46 lines (34 loc) Ā· 1.22 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
46
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 ā 1,3,2
3,2,1 ā 1,2,3
1,1,5 ā 1,5,1
public void nextPermutation(int[] nums) {
int k = nums.length-2;
while(k>=0 && nums[k]>=nums[k+1])k--;
//CASE 1
if(k==-1){
reverseArray(0,nums.length-1,nums);
return;
}
//CASE 2
for(int i = nums.length-1;i>k;i--){
if(nums[i]>nums[k]){//2
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
break;
}
}
reverseArray(k+1,nums.length-1,nums);
}
void reverseArray(int i,int j,int[] nums){
while(i<j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;j--;
}
}