Easy to understand solution O(nlogn)


#1

vector Solution::nextPermutation(vector &a) {
int n=a.size();
int c=0;
for(int i=n-1;i>0;i–)
{
if(a[i]<a[i-1])
{
c++;
}
else break;
}
if(c==n-1)
{
reverse(a.begin(),a.end());
return a;
}
int j=0;
int i=n-1;
for(;i>0;i–)
{
if(a[i]>a[i-1])
{
j=i;
break;
}
}
int k=n-1;
for(;k>=j;k–)
{
if(a[k]>a[i-1])
{
break;
}
}
swap(a[i-1],a[k]);
sort(a.begin()+j,a.end());
return a;
}.