-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
I have added the solution of Q31 (Next Permutation in CPP ) of leetcode.
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
|
||
class Solution { | ||
public: | ||
void nextPermutation(vector<int>& a) { | ||
int idx=-1; | ||
|
||
int n = a.size(); | ||
for(int i=n-1; i>0; i--){ | ||
if(a[i]>a[i-1]){ | ||
idx=i; | ||
break; | ||
} | ||
} | ||
if(idx == -1){ | ||
reverse(a.begin(), a.end()); | ||
}else{ | ||
int prev = idx; | ||
for(int i=idx+1; i<n; i++){ | ||
if(a[i]>a[idx-1] and a[i]<=a[prev]){ | ||
prev=i; | ||
} | ||
} | ||
swap(a[idx-1],a[prev]); | ||
reverse(a.begin()+idx,a.end()); | ||
} | ||
} | ||
}; |