leetcode : next permutation

本文介绍了一个算法问题——如何找出比当前序列大的下一个排列。通过详细步骤解析,包括寻找关键元素、进行元素交换及部分序列反转等操作,实现了原地替换,避免了额外内存分配。

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

 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.

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

 

首先要明白什么是next permutation. 

 

 转leetcode solution : 

(1) 在当前序列中,从尾端往前寻找到第一对两个相邻元素,前一个记为first,后一个记为second,这对元素满足first 小于 second。

(2) 然后再从尾端寻找另一个元素number,如果满足first 小于number,即将第first个元素与number元素对调,并将second元素之后(包括second)的所有元素颠倒排序,即求出下一个序列

example:
6,3,4,9,8,7,1
此时 first = 4,second = 9
从尾到前找到第一个大于first的数字,就是7
交换4和7,即上面的swap函数,此时序列变成6,3,7,9,8,4,1
再将second=9以及以后的序列重新排序,让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列
得到最终的结果:6,3,7,1,4,8,9

 

public class Solution {
    /* 
    (1) 从后往前,找到第一个nums[i] < nums[i+1]的i
    (2) 从 nums[length -1]开始往i + 1 开始找,找到第一个大于nums[i]的数,交换之
    (3) 将nums[i+1 ~ length - 1] 的数reverse
    */
    public void nextPermutation(int[] nums) {
        if(nums == null || nums.length <= 1) {
            return;
        }
        
        int length = nums.length - 1;
        
        int i = length;
        for(; i >= 1; i--) {
            if(nums[i - 1] < nums[i]) {
                break;
            }
        }
        
        if(i != 0) {
            swap(nums, i - 1);
        }
            
        reverse(nums, i, length);
    
    }
    
    public void swap(int[] nums, int i) {
        
        for(int j = nums.length - 1; j > i; j--) {
            if(nums[j] > nums[i]) {
                swap(nums, i, j);
                break;
            }
        }
    }
    
    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    public void reverse(int[] nums, int i, int j) {
        while(i < j) {
            swap(nums, i , j);
            j--;
            i++;
        }
    }
}

  

转载于:https://www.cnblogs.com/superzhaochao/p/6406006.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值