#190 Next Permutation II
来源:互联网 发布:阿里巴巴云计算张北 编辑:程序博客网 时间:2024/06/17 01:34
题目描述:
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).
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
The replacement must be in-place, do not allocate extra memory.
这题怎么说呢,就是重在观察。从数组的后面往前看:如果nums[i] < nums[i - 1],这是没问题的;一旦nums[i] > nums[i - 1],这个应有的顺序就乱了,那么从nums[i - 1]开始,我们就可以从新排序得到next permutation。
举个例子来说:[1,1,5,4,2,7,6,4,3]
后面的7,6,4,3都没有问题,问题在2,7这里。找到2所在的index之后,可以发现next permutation应该是1,1,5,4,3,xxxx。这个3是怎么来的呢?这个3是在2,7,6,4,3这些数中大于2的最小数。所以算法中就是要寻找index - 1的坐标之后大于nums[index - 1]的最小数,用来替换index - 1的位置。
搞定这些之后就好办了,把剩下的数从小到大排序一下就是答案了。
Mycode(AC = 14ms):
class Solution {public: /** * @param nums: a vector of integers * @return: return nothing (void), do not return anything, modify nums in-place instead */ void nextPermutation(vector<int> &nums) { // write your code here if (nums.size() <= 1) return; // find the index of number where nums[index] > nums[index - 1] int index = -1; for (int i = nums.size() - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { index = i; break; } } // if index not found, then it is already largest number if (index == -1) { reverse(nums.begin(), nums.end()); } else { // find the min number which is larger than nums[index - 1], // in the index ~ end int second_min = nums[index], smin_idx = index; for (int i = index + 1; i < nums.size(); i++) { if (nums[i] > nums[index - 1] && nums[i] < second_min) { second_min = nums[i]; smin_idx = i; } } // swap the min number with nums[index - 1] int tmp = nums[index - 1]; nums[index - 1] = nums[smin_idx]; nums[smin_idx] = tmp; // sort numbers after index - 1 sort(nums.begin() + index, nums.end()); } }};
- #190 Next Permutation II
- LintCode_190 Next Permutation II
- Next Permutation II
- [LeetCode] Next Permutation、Permutations、Permutations II、Permutation Sequence
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- N-Queens && II and Permutations && II && Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- android中MVP模式(一)
- http状态码
- 读取其他进程的数据
- Java连接MySQL数据库及简单操作代码
- win7 64位系统,打开sql server 2012,鼠标不能用的处理办法
- #190 Next Permutation II
- gitlab jenkins 等服务的迁移
- 【Python】Python 在Window环境下的搭建
- SlidingMenu的详细介绍
- 8.3 魔鬼(no.31~no.32)
- 数据结构.树的分类 思维导图
- 大数据时代的技术hive:hive的数据类型和数据模型
- PHP10问——PART 1
- ceph的pool创建流程--代码分析