-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext_Permutation.cpp
More file actions
29 lines (28 loc) · 873 Bytes
/
Next_Permutation.cpp
File metadata and controls
29 lines (28 loc) · 873 Bytes
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
//O(N)
class Solution {
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=num.size()-1;
bool sign=false;
for(;i>0;i--)
{
if(num[i]>num[i-1])
{
sign=true;
int j=i;
//could binary search here, but still O(N)
while(j<num.size()&&num[j]>num[i-1])
{
j++;
}
j--;
swap(num[i-1], num[j]);
reverse(num.begin()+i,num.end());
break;
}
}
if(!sign)reverse(num.begin(),num.end());
}
};