zoukankan      html  css  js  c++  java
  • 45.leetcode31_next_permutation

    1.题目描述

    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.

    在不申请额外空间的情况下将nums数组中的数字重新排序,新构成的“数字”是所有可能的“数字”中比当前“数字”大的最小的。

    如果不存在这个“数字”,返回nums重新排序后的最小“数字”。

    Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
    1,2,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    2.题目分析

    ①不需要返回任何值②在不申请额外空间的情况下改变nums数组顺序

    3.解题思路

    我是从后向前遍历,找到第一个降序数字。将其之后的数字重新排序,找到第一个比其大的数字进行交换,然后重新整合nums数组。

    Python(87ms)

    class Solution(object):
        def nextPermutation(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            l=len(nums)-1
            max=nums[l]
            l-=1
            while l>=0:
                if nums[l]>=max: 
                    max=nums[l]
                else:
            #这里不知道算不算是申请了额外空间
                    temp=nums[l:] 
                    temp.sort()
                    i=0
                    for i in range(len(temp)):
                        if temp[i]>nums[l]:
                            nums[l]=temp[i]
                            temp=temp[:i]+temp[i+1:]
                            for k in range(len(temp)):
                                n=nums[l+k+1]
                                nums[l+k+1]=temp[k]
                            break
                    break
                l-=1
            if l==-1:
                nums=nums.sort()
  • 相关阅读:
    【职业规划】一位资深程序员大牛给予Java初学者的学习路线建议
    一个断点调试的小技巧
    无穷分数
    Spring事务异常回滚,捕获异常不抛出就不会回滚
    理解Servlet和Servlet容器、Web服务器等概念
    图解红黑树及Java进行红黑二叉树遍历的方法
    Majority Element
    Factorial Trailing Zeroes
    Valid Parentheses
    House Robber
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8486359.html
Copyright © 2011-2022 走看看