zoukankan      html  css  js  c++  java
  • 31. Next Permutation (下一个全排列)

    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

     1 class Solution:
     2 
     3     def nextPermutation(self, a):
     4         """
     5         :type nums: List[int]
     6         :rtype: void Do not return anything, modify nums in-place instead.
     7         """
     8         def swap(a, i, j):
     9             temp = a[i]
    10             a[i] = a[j]
    11             a[j] = temp
    12 
    13         def reverces(a, i):
    14             for k in range(int((len(a) - i) / 2)):
    15                 swap(a, i + k, len(a) - k - 1)
    16 
    17         # 后找
    18         i = len(a) - 2
    19         while(i>=0 and a[i + 1] <= a[i]):
    20             i -= 1
    21 
    22         # 小大
    23         if(i >= 0):
    24             j = len(a) - 1
    25             while j >= 0 and a[j] <= a[i]:
    26                 j -= 1
    27             # 交换      
    28             swap(a, i, j)
    29             # 反转
    30         reverces(a, i+1)
  • 相关阅读:
    大文件上传
    zabbix接口
    Vue 在不同的环境使用不同的接口地址
    Vue发布流程
    RabbitMQ集群一些使用细节
    Watcher 系统整体流程图
    监控系统各个模块部署
    deepin安装node和npm最新
    google安装json插件
    数据库访问性能优化 Oracle
  • 原文地址:https://www.cnblogs.com/zle1992/p/8538649.html
Copyright © 2011-2022 走看看