标签:leetcode
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, do not allocate 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
基本思想:
这儿由于数组是反向遍历的,所以可以使用使用stl中的反向迭代器。
runtime:12ms
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size()<2) return ;
auto iter=nums.rbegin();
while(iter!=(nums.rend()-1)&&*iter<=*(iter+1))
iter++;
if(iter==nums.rend()-1)
sort(nums.begin(),nums.end());
else
{
auto upper=iter;
auto tmp=nums.rbegin();
for(;tmp!=iter;tmp++)
{
if(*tmp>*(iter+1))
{
if(*tmp<*upper)
{
upper=tmp;
}
}
}
swap(*(iter+1),*upper);
sort(nums.rbegin(),iter+1,greater<int>());
}
}
};
标签:leetcode
原文地址:http://blog.csdn.net/u012501459/article/details/46423249