您的位置:首页 > 其它

Middle-题目88:31. Next Permutation

2016-05-31 17:26 337 查看
题目原文:

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

题目大意:

求出一个数组的下一个字典序的排序结果。

题目分析:

使用C++中的库函数next_permutation实现(在头文件algorithm中)。

函数接口:bool next_permutation( iterator start, iterator end);

即求start-end这个序列的下一个排序。

源码:(language:cpp)

class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
};


成绩:

12ms,beats 10.04%,众数12ms,88.95%

Cmershen的碎碎念:

C++11中,Next_permutation的源码如下:

bool _Next_permutation(_BidIt _First, _BidIt _Last, _Pr _Pred)
{   // permute and test for pure ascending, using _Pred
_BidIt _Next = _Last;
if (_First == _Last || _First == --_Next)
return (false);

for (; ; )
{   // find rightmost element smaller than successor
_BidIt _Next1 = _Next;
if (_DEBUG_LT_PRED(_Pred, *--_Next, *_Next1))
{   // swap with rightmost element that's smaller, flip suffix
_BidIt _Mid = _Last;
for (; !_DEBUG_LT_PRED(_Pred, *_Next, *--_Mid); )
;
_STD iter_swap(_Next, _Mid);
_STD reverse(_Next1, _Last);
return (true);
}

if (_Next == _First)
{   // pure descending, flip all
_STD reverse(_First, _Last);
return (false);
}
}
}


大致思路:

在当前序列中,从尾端向前寻找两个相邻元素,前一个记为*i,后一个记为*t,并且满足*i < *t。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元素颠倒排序,即求出下一个序列了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: