leetcode: 31. Next Permutation
来源:互联网 发布:淘宝分销平台骗局 编辑:程序博客网 时间:2024/05/18 03:47
Problem
# coding=utf-8# 假设数组中所有数值组成的排列组合是个循环列表,则返回该输入组合的下一组合。## 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
Translation
假设数组中所有数值组成的排列组合是个循环列表,则返回该输入组合的下一组合。
Ideas
nums[k:]的盈满则亏之演。
AC
# Time: O(n)# Space: O(1)class Solution(): def nextPermutation(self, nums): k, l = -1, 0 for i in range(len(nums) - 1): if nums[i] < nums[i + 1]: k = i # 保证了k之后必定是降序的 if k == -1: nums.reverse() # 全称降序,那还找个毛,直接回到循环列表表首咯 (。・・)ノ return for i in range(k + 1, len(nums)): if nums[i] > nums[k]: # 免得从后面拉出来一个比 nums[k] 还小的,那就搞笑了 l = i # 因为k之后必定是降序的,所以最后跑出来的l必定是k之后 比nums[k]大的最小元素 的下标, nums[k], nums[l] = nums[l], nums[k] nums[k + 1:] = nums[:k:-1] # 每次对于 nums[k:] 来说,都是一次overflow,所以一定是从最满(降序)变成最底(升序)if __name__ == "__main__": nums = [1, 4, 3, 2] Solution().nextPermutation(nums) assert nums == [2, 1, 3, 4]
阅读全文
1 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31. Next Permutation
- 【leetcode】31. Next Permutation
- LeetCode *** 31. Next Permutation
- leetcode 31. Next Permutation
- 学习:C#连接MySQL数据库
- HDU-2021(发工资咯:))
- 被正确使用的轮子才是好轮子——使用Construct2制作游戏的一点感想
- Unity坐标系
- 摩尔定律还有效吗
- leetcode: 31. Next Permutation
- 算法系列(7)leetcode 206
- General error: 2006 MySQL server has gone away
- CNTK API文档翻译(17)——多对多神经网络处理文本数据(1)
- Python2.7 安装激活
- 贪心算法-看节目
- Win10 Install Ubuntu Via Hyper-v
- Fresco使用
- C语言中标识符的作用域、命名空间、链接属性、生命周期、存储类型