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)
成绩:
12ms,beats 10.04%,众数12ms,88.95%
Cmershen的碎碎念:
C++11中,Next_permutation的源码如下:
大致思路:
在当前序列中,从尾端向前寻找两个相邻元素,前一个记为*i,后一个记为*t,并且满足*i < *t。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元素颠倒排序,即求出下一个序列了。
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)的所有元素颠倒排序,即求出下一个序列了。
相关文章推荐
- Jmeter中引入class文件的方法
- Jmeter中引入class文件的方法
- Html基础知识详解
- WordCount
- iOS应用内语言切换功能
- iOS View 模糊效果(毛玻璃)
- JSONObject和JSONArray
- 2016百度知道网络引流技术
- 在C#代码中应用Log4Net(三)Log4Net中配置文件的解释
- Java之——使用JMX监控Tomcat
- 报数
- 第13周项1—分数类中的运算符重载 (2)
- C# SendMessage用法
- 地址栏中输入IP地址提示指定的网络名不再可用的解决方法
- 第十四周项目2.2—两个成员的类模板
- Powerdesigner逆向工程
- 视频切分与合并
- 地图定位
- iOS \'The sandbox is not sync with the Podfile.lock\'问题解决
- makesfx.exe (Make SFX (Self-extracting archive))