Next Permutation
来源:互联网 发布:种植牙费用 知乎 编辑:程序博客网 时间:2024/06/10 20:02
题目:
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
思想:
由题意可知,我们需要讨论两种情况,
第一种情况是,所组成的数已经是最大的数,我们需要输出一个最小的数。
第二种情况是,仍存在一个较大的数。
从后向前遍历数组,若发现,所有数均是逆序排序的,则对其排序,输出结果。否则,逆序遍历数组,找到第一个满足小于当前元素的数,并将二者置换,注意,此时由于发生元素的交换,为保证该数大于原数的最小数,需将置换位后的数据进行顺序排序。
代码:
class Solution {public:void nextPermutation(vector<int>& nums) {int length = nums.size();int k = -1;for ( int i = length-2; i >= 0; i--){if (nums[i]>=nums[i + 1])continue;elsek = i;break;}if (k == -1)//处理已是最大数的情况{ sort(nums.begin(),nums.end());}else{int index = -1;for (int i = length-1; i > k; i--){if (nums[i] > nums[k]){index = i;break;}}swap(nums[k], nums[index]);sort(nums.begin()+k + 1, nums.end());}}};
0 0
- 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
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- [关键字]const用法集锦
- 深拷贝的一种实现方法
- 手机游戏刷表流程记录—服务端菜鸟的成长之路
- Ubuntu15.04编译php
- redis错误集
- Next Permutation
- Android应用setContentView与LayoutInflater加载解析机制源码分析
- IntelliJ 出现 cannot resolve symbol.
- Android Studio 报No resource found that matches the given name '@style/Theme.AppCompat.Light'.
- X-code beta 开发iWatch项目,运行没有错误,但是某些操作一点就崩,而且找不错误的原因场景一
- StringUtils工具类用法
- Android命令
- opencv学习(一)书本《学习Opencv》(中文版)的第二章的10个入门样例的分析
- poj 1797 Heavy transportation 最短路