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()
  • 相关阅读:
    [ZJOI2010]count 数字计数
    小雄数
    简单筛法函数
    [Noip模拟题]lucky
    欧拉线筛
    Intern Day78
    CodeForces1360C
    CodeForces1373B
    Intern Day78
    Intern Day78
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8486359.html
Copyright © 2011-2022 走看看