45.leetcode31_next_permutation

本文介绍了一个在不使用额外空间的情况下寻找并实现数组中下一个字典序较大排列的方法。通过从后向前遍历数组找到第一个降序元素,然后对该元素之后的部分进行调整以形成新的排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/19991201xiao/p/8486359.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值