• 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()
  • 相关阅读:
    安卓版php服务器的mysql数据库增删改查简单案例
    PHP之Mysql常用SQL语句示例的深入分析
    PHP文件上传主要代码讲解
    只能输入数字的文本框-php
    Unknown column '' in 'field list'解决方案
    PHP mysqli连接MySQL数据库
    Php连接及读取和写入mysql数据库的常用代码
    mysqli 操作数据库
    类的静态变量访问
    用JS添加文本框案例代码
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8486359.html
Copyright © 2020-2023  润新知