forked from Ritesh25696/interviewBit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation
More file actions
47 lines (34 loc) · 1.41 KB
/
Next Permutation
File metadata and controls
47 lines (34 loc) · 1.41 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
47
Implement the next permutation, which rearranges numbers into the numerically next greater permutation of numbers.
If such arrangement is not possible, it must be rearranged as the lowest possible order ie, sorted in an ascending order.
The replacement must be in-place, do not allocate extra memory.
Examples:
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
20, 50, 113 → 20, 113, 50
Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
***************************************************************************************************************
step:-
step 1: find maximum i for which A[i]<A[i+1].
Step 2: find max j where(j>i) for which A[j]>A[i], obviously such j exist (i+1) .
Step 3: swap A[i] and A[j] and reverse all elements after i.
****************************************************************************************************************
void Solution::nextPermutation(vector<int> &A) {
int max_i = -1;
for(int i=0 ;i<A.size()-1 ; i++){
if(A[i]<A[i+1]){
max_i = i;
}
}
if(max_i == -1){
sort(A.begin() , A.end());
}
else{
int max_j = A.size()-1;
while(A[max_j] < A[max_i]){
max_j--;
}
swap(A[max_j],A[max_i]);
sort(A.begin()+max_i+1,A.end());
}
}