zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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 and use only constant 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

    思路


         这道题最直观的思路就是直接将数组先进行排序,然后此次输出排序组合,知道找到当前的排列并输出下一个排列。但是时间复杂度较高。时间复杂度为O(n!),空间复杂度为O(n).

      当然这不是最优的解法,还有一种是利用排列的规律对数组进行变化,这样可以直接得到下一个排列。方法是我们从右边开始向前查找,知道找到满足a[i-1] < a[i] 的情况,然后我们在a[i]开始查找,知道找到一个满足 a[ j+1] < a[i-1] < a[ j] 的情况。最后对a[i]到尾部进行反转。得到下一个排列。时间复杂度为O(n),空间复杂度为O(1)。

    图示


       ·

       

       

    解决代码


     1 class Solution:
     2     def nextPermutation(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: void Do not return anything, modify nums in-place instead.
     6         """
     7         length = len(nums)
     8         i = length - 2
     9         while i >=0 and nums[i+1] <= nums[i]:   #找到第一个nums[i+1] > nums[i]的下标
    10             i -= 1
    11         if i >= 0:                               # 如果i等于0,表示没有找到。直接将数组反转就可以得到结果。
    12             j = length -1                        # 从最后一个数字开始查找
    13             while j>=0 and nums[i] >= nums[j]:        # 知道找到第一个满足 nums[j] > nums[i]的下标
    14                 j -= 1
    15             nums[i], nums[j] = nums[j], nums[i] # 交换两个位置
    16          
    17         start = i + 1
    18         end = length -1 
    19         while start < end:                       # 对i下标后面的进行反转,得到结果。
    20             nums[start], nums[end] = nums[end], nums[start]
    21             start += 1
    22             end -= 1
  • 相关阅读:
    php yield学习笔记(一)
    EasySwoole的ContextManager的分析和使用
    Easyswoole的WaitGroup和Csp组件的分析和使用
    Laravel Event的分析和使用
    Laravel驱动管理类Manager的分析和使用
    Laravel Exception结合自定义Log服务的使用
    vue基础
    vue.js
    改善项目组织
    MongoDB 4.0版
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10669668.html
Copyright © 2011-2022 走看看