前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 31. Next Permutation

leetcode: 31. Next Permutation

作者头像
JNingWei
发布2018-09-28 11:48:41
3640
发布2018-09-28 11:48:41
举报
文章被收录于专栏:JNing的专栏

Problem

代码语言:javascript
复制
# 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

代码语言:javascript
复制
假设数组中所有数值组成的排列组合是个循环列表,则返回该输入组合的下一组合。

Ideas

代码语言:javascript
复制
nums[k:]的盈满则亏之演。

AC

代码语言:javascript
复制
class Solution():
    def nextPermutation(self, x):
        pre, later = -1, 0
        for i in range(len(x) - 1):
            if x[i] < x[i + 1]:
                pre = i    # [pre+1:len(x)]为全数组中最后一个降序。
        if pre == -1:
            x.reverse()    # 全程降序,那还找个毛,直接回到循环列表表首咯 (。・・)ノ
            return
        for i in range(pre + 1, len(x)):
            if x[i] > x[pre]:
                later = i    # 因为k之后必定是降序的,所以最后跑出来的l必定是k之后 比 x[pre] 大的最小元素 的下标。
        x[pre], x[later] = x[later], x[pre]
        x[pre + 1:] = x[:pre:-1]    # 每次对于 x[pre:] 来说,都是一次overflow,所以一定是从最满(降序)变成最底(升序)


if __name__ == "__main__":
    nums = [1, 4, 3, 2]
    Solution().nextPermutation(nums)
    assert nums == [2, 1, 3, 4]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年11月11日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem
    • Translation
      • Ideas
      • AC
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档