Middle-题目88:31. Next Permutation
来源:互联网 发布:张兆艺淘宝店 编辑:程序博客网 时间:2024/06/05 05:41
题目原文:
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)的所有元素颠倒排序,即求出下一个序列了。
- Middle-题目88:31. Next Permutation
- LeetCode算法题目:Next Permutation
- Middle-题目93:60. Permutation Sequence
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 在C#代码中应用Log4Net(三)Log4Net中配置文件的解释
- JSONObject和JSONArray
- MVC
- Jmeter中引入class文件的方法
- C#繁体转简体批量工具(完整代码)
- Middle-题目88:31. Next Permutation
- Android消息机制
- 代码 实现按钮 seletor shape 选择器等
- SpringMVC、Zookeeper、Dubbo使用
- Java继承和多态
- Android中采用线程池进行线程的管理
- Android--从零单排系列(4)--常用对话框和DialogFragment的优势
- Spark安装
- Android中Textview加横线的属性