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)。

图示


   ·

   

   

解决代码


 class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
i = length - 2
while i >=0 and nums[i+1] <= nums[i]: #找到第一个nums[i+1] > nums[i]的下标
i -= 1
if i >= 0: # 如果i等于0,表示没有找到。直接将数组反转就可以得到结果。
j = length -1 # 从最后一个数字开始查找
while j>=0 and nums[i] >= nums[j]: # 知道找到第一个满足 nums[j] > nums[i]的下标
j -= 1
nums[i], nums[j] = nums[j], nums[i] # 交换两个位置 start = i + 1
end = length -1
while start < end: # 对i下标后面的进行反转,得到结果。
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1

最新文章

  1. PHP 中的行为 ,与什么是切面
  2. [转]Linux查看物理CPU个数、核数、逻辑CPU个数
  3. 配置Java EE Eclipse+Tomcat开发环境
  4. PHP(一)
  5. Button控件
  6. Android 6.0 双卡拨号
  7. Tag Helpers 介绍
  8. C#进程启动实例
  9. 电子科大POJ &quot;统计单词&quot;
  10. 分页控件AspNetPager学习笔记
  11. jsp传到java的control层的方法
  12. Mysql(六):数据备份、pymysql模块
  13. 华为6.0系统设备最完美激活Xposed框架的经验
  14. javascript进阶之AJAX
  15. C#泛型。
  16. 创建两个SAP系统之间的RFC信任关系
  17. Highcharts之3D柱状图
  18. 图论之二分图-HihoCoder1121
  19. leetcode 300最长上升子序列
  20. PHP解决搜索时在URL地址栏输入中文字符搜索结果出现乱码

热门文章

  1. day_6.26 反射
  2. h5 打造全屏体验 element.requestFullscreen()
  3. Python2安装igraph
  4. SecureCRT安装使用
  5. gulp安装及使用流程
  6. 更新快排中的partition
  7. [No0000F8]override和new的区别
  8. Mac开发博客摘录
  9. 如何写好.babelrc?Babel的presets和plugins配置解析
  10. MVC 实用架构设计(〇)——总体设计