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]