[LeetCode]Next Permutation
2015-08-08 21:57
351 查看
题目
Number: 31Difficulty: Medium
Tags: Array
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.
[code]1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1
题解
寻找一个排列的下一个排列。下一个排列是指比原排列大的最小一个排列。如果不存在,那么返回排列的逆序。
解题思路:
从后向前,寻找第一个非升序的数字,比如
4, 5, 8, 6, 3, 1,找到5;
在5后面的序列中,从后向前寻找第一个比5大的数字,找到6;
交换5和6,即
4, 6, 8, 5, 3, 1;
把6后面的序列逆序,即
4, 6, 1, 3, 5, 8。
代码
[code]void nextPermutation(vector<int>& nums) { int n = nums.size() - 1; while(n > 0 && nums[n-1] >= nums ) n--; if(!n) { reverse(nums.begin(), nums.end()); return; } int change = n - 1; n = nums.size() - 1; while(n > change && nums[change] >= nums ) n--; swap(nums , nums[change]); reverse(nums.begin() + change + 1, nums.end()); }
总结
看到一个答案,重复利用STL标准库。[code]void nextPermutation(vector<int>& nums) { auto i = is_sorted_until(nums.rbegin(), nums.rend()); if(i != nums.rend()) swap(*i, *upper_bound(nums.rbegin(), i, *i)); reverse(nums.rbegin(), i); }
参考:
1, 4, 11 lines C++
相关文章推荐
- 通过jacob操作office
- 2015第32周六
- JAVA学习篇--JSTL基金会
- 字符编码详解
- Hdfs本地短路读取文件
- 华为OJ(学英语)
- Hibernate 性能优化及缓存的使用
- Android 获取子组件
- Hive配置优化
- WebService中SOAP1.1和1.2分析
- 整理Linux关机命令
- Hive0.14数据存储优化
- 今天带来的是一个对图书编号和价格设定程序 不是很完善希望大家给与建议进行修改
- poj2406 KMP
- 开始了他的高速功率矩阵
- 面试的算法1(C语言)(整理)(组合数 字符串倒置 最大公共串)
- Quorum/NRW机制
- 聚集索引和非聚集索引的区别
- Python学习笔记一
- 2015 Multi-University Training Contest 6