31. Next Permutation
2017-08-22 09:51
183 查看
31. Next Permutation
问题描述: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
解读题意:题目在说啥?下一个排序的意思其实就是,给你一些数字的排列,输入某个排序A,从这些数字组成的全排列中,选出排在A后一位的排序B。例如1,2,3的全排列如下,A= 2 1 3,它的下一个排序就是B = 2 3 1
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
解题思路:直接贴张外文文献的解题方法图
1.从右向左找严格升序,找到第一个打破升序(等于也是打破的一种情况)的数字
A,下标为 index ,如图 数字 6一样
2.从右向左找第一个大于等于第一步中的数字A的数
B ,例如图中数字 7
3. 交换 A B的值
4. 逆序 index 下标之后的所有数
下面给出Python代码
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ start = 0 end = len(nums) - 1 while end > start and nums[end] <= nums[end - 1]: end -= 1 if end == start: # 原序是个升序列, 直接逆序操作 nums.reverse() return partion = end - 1 end = len(nums) - 1 while end > partion and nums[partion] >= nums[end]: end -= 1 change = end nums[partion], nums[change] = nums[change], nums[partion] # 交换两个数 nums[partion + 1:] = nums[partion + 1:][::-1] # 逆序partion后的所有数字
欢迎点赞,留言交流
相关文章推荐
- 个人总结百种网站推广方式(31-60)
- python类库31[python的libpath]
- python类库31[正则表达式之sub]
- [转]Ultra Fractal教程系列31——关于变换的学习06——添加框架
- 《那些年啊,那些事——一个程序员的奋斗史》——31
- Study WP7 3:Windows Phone 31 days of Study
- 10-31
- 稳扎稳打Silverlight(31) - 2.0Tip/Trick之加载XAP, 加载XAML, 加载DLL, AppManifest.xaml文件说明, 自定义鼠标指针
- 基于visual c++之windows核心编程代码分析(31)SNMP协议编程
- HDU 4155 The Game of 31
- LInux下常用压缩格式的解压和压缩(转自http://www.21ds.net/article/31/369)
- 牛腩购物网31:首页修改(商品销售排行) 查询的行数,字段,表名不能使用参数化传值,而只能用拼接字符串的方式传值
- python 31常用模块介绍(转)
- VIM用户手册 For Vim version 7.3. *usr_31.txt*
- [技巧] 31 个常用的 Safari 快捷键
- 2009年上半年网工考试试题分析31-40
- Windows Phone 7 开发 31 日谈——第11日:加速感应器
- VC++2012编程演练数据结构《31》狄杰斯特拉算法
- Windows 8开发31历程---第一天: 一个的空白应用程序
- 面试题 31: 求子数组的最大和