LeetCode Next Permutation
来源:互联网 发布:linux rpm命令 编辑:程序博客网 时间:2024/04/28 10:38
LeetCode解题之Next Permutation
原题
找出一个数组按字典序排列的后一种排列。
注意点:
- 如果原来就是字典序排列中最大的,将其重新排列为字典序最小的排列
- 不要申请额外的空间
- 小心数组越界问题
- 函数没有返回值,直接修改列表
例子:
输入: [1,2,3]
输出: [1,3,2]
输入: [3,2,1]
输出: [1,2,3]
解题思路
通过一个例子来说明,原数组为[1,7,3,4,1]。我们想要找到比173421大一点的数,那就要优先考虑将后面的数字变换顺序,而421从后往前是升序的(也就是这三个数字能组成的最大的数),变换了反而会变小,所以要先找到降序的点。可以看出3是第一个降序的点,要想整个数变大,3就要变大,从后往前找到第一个比3大的数4,将3和4交换位置得到174321,既然原来3所在位置的数字变大了,那整个数肯定变大了,而它之后的数是最大的(从后往前是升序的),应转换成最小的,直接翻转。
AC源码
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) targetIndex = 0 changeIndex = 0 for i in range(length - 1, 0, -1): if nums[i] > nums[i - 1]: targetIndex = i - 1 break for i in range(length - 1, -1, -1): if nums[i] > nums[targetIndex]: changeIndex = i break nums[targetIndex], nums[changeIndex] = nums[changeIndex], nums[targetIndex] if targetIndex == changeIndex == 0: nums.reverse() else: nums[targetIndex + 1:] = reversed(nums[targetIndex + 1:])
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- [LeetCode]Next Permutation
- LeetCode-Next Permutation
- [leetcode]Next Permutation
- LeetCode - Next Permutation
- LeetCode 31: Next Permutation
- 【leetcode】Next Permutation
- LeetCode题解:Next Permutation
- 【LeetCode】Next Permutation
- [LeetCode] Next Permutation
- LeetCode Next Permutation
- leetCode | Next Permutation
- ScrollView嵌套ListView冲突的最简洁解决方案
- PHP运行环境之IIS FastCGI 进程意外退出解决办法
- 初试jni
- SQL查询月份有多少天(根据变量)
- 关于微信公众平台表情代码的记录
- LeetCode Next Permutation
- 收集的伪静态中经常使用的一些参数解释,如[NC,L,QSA]等
- PHP通过计算经纬度获取附近的数据信息
- 在Windows下搭建Gitlab服务器(二)-不能访问Gitlab的web管理页面
- C# 操作JSON字符串用于与网页中的返回数据进行互动
- PHP 在源码中实现换行使得页面源码更精致美观
- 目前计划---毕业前(2016-6)
- 完全卸载oracle11g步骤
- 黑马程序员--OC自学笔记---06简单电影购票系统