【Leet Code】31. Next Permutation---Medium
2015-11-20 15:36
232 查看
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)从最右边向左边遍历,找到第一个左边的数小于右边的数的位置fir;
2)如果fir==0,则说明原来数据是从大到小排序的,此时将整个数组翻转即可;
3)否则,先--fir,令fir指向第一个需要被交换的数,然后从右向左遍历找到第一个比fir的值大的数的位置sec,交换fir和sec的值,将fir后面的数据从小到大排序。
代码实现:
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
思路:
1)从最右边向左边遍历,找到第一个左边的数小于右边的数的位置fir;
2)如果fir==0,则说明原来数据是从大到小排序的,此时将整个数组翻转即可;
3)否则,先--fir,令fir指向第一个需要被交换的数,然后从右向左遍历找到第一个比fir的值大的数的位置sec,交换fir和sec的值,将fir后面的数据从小到大排序。
代码实现:
class Solution { public: void nextPermutation(vector<int>& nums) { int fir = nums.size() -1, sec = nums.size() -1; //先找到第一个比前面比后面大的数的位置。如[4,2, 0, 2, 3, 2, 0]里面2,3值2<3 while(fir > 0 && nums[fir] <= nums[fir - 1]) --fir; //如果是最大数,即题目中的If such arrangement is not possible, it must rearrange it as the lowest possible order成立 if(fir == 0) { reverse(nums.begin(), nums.end()); return; } --fir; //令fir指向第一个要被交换的元素 while(sec > fir && nums[sec] <= nums[fir]) --sec; swap(nums[fir], nums[sec]); //将新交换位置后面的所有数字从小到大排序 sort(nums.begin()+fir+1, nums.end()); } };
相关文章推荐
- Ubuntu初体验
- Codeforce#331 (Div. 2) A. Wilbur and Swimming Pool(谨以此题来纪念我的愚蠢)
- mongodb 在Linux下的增删改查和用nodejs连接mongodb
- 【转】JMeter基础之——一个简单的性能测试
- Spring、Struts2+Spring+Hibernate整合步骤
- 《需求分析与系统设计》读书笔记之二
- android studio 使用 SVN
- Tomcat中server.xml文件详细配置介绍
- jquery 操作select
- javax.comm初步探索
- smokeping 安装流程
- osg中的矩阵计算
- cookie存取
- GWT+CodeTemplate+TableCreate快速开发
- java 每日习题(七)统计字符串中字母、空格、数字和其它字符的个数
- APP存放路径及log信息
- shader着色器
- Nginx配置https访问
- java学习资源大集锦
- Placement new的用法及用途