【Leetcode】【python】Next Permutation
来源:互联网 发布:大麦dm1016破解网络锁 编辑:程序博客网 时间:2024/05/22 04:48
题目大意
寻找一组数排序的下一个序列
例如:1,2,3,下一个就是1,3,2
解题思路
这题没看懂题目前一头雾水,最后再看看原题说明终于懂了。
网上有一种经典的解法,这里引用一张图片,其说明了整个步骤:
跟着步骤来,这题的代码就十分简单了。
代码
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ partition = -1 for i in range(len(nums)-2, -1, -1): # 从倒数第二个数开始遍历到第0个数 if nums[i] < nums[i+1]: # 从后向前找到第一个升序对,并让partition等于升序对中较小的 partition = i break if partition == -1: # 没找到升序对 e.g. 54321 --> 12345 nums.reverse() else: for i in range(len(nums)-1, partition, -1): # 交换partition和升序对后面比partition更大的数 如14532 -> 15432 if nums[i] > nums[partition]: nums[i], nums[partition] = nums[partition], nums[i] break # 将partition后面的数字逆向排序。由于找到的partition是从后向前的第一个升序对,所以可以放心partition后面一定都是降序的 # 所以逆向排序后可以得到一个新的刚好大于之前permutation的next permutation # 比如此时14532已经变为15432,则再将5(此时partition已经是5了)后面的432逆序排列得到234.则最终的数字变为15234 nums[partition+1:len(nums)] = nums[partition+1:len(nums)][::-1] # 切片
总结
阅读全文
0 0
- 【Leetcode】【python】Next Permutation
- 31. Next Permutation Leetcode Python
- [leetcode: Python]31.Next Permutation
- leetcode 日经贴,python code -Next Permutation
- [LeetCode] 031. Next Permutation (Medium) (C++/Python)
- 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
- Lintcode114 Unique Paths solution 题解
- Lintcode115 Unique Paths || solution 题解
- read file write
- Adobe Acrobat Reader DC 离线安装包
- PAT 1087. All Roads Lead to Rome (30)
- 【Leetcode】【python】Next Permutation
- FTPrep, 57 Insert interval
- 2017-9-7-第一篇博客
- android使用xml定义背景边框
- PHPforeach()跳出本次或当前循环与终止循环方法
- 单道进程
- 常用html标签复习
- 机器学习中的k-means聚类及其Python实例
- frame与iframe的用法与区别