下一个排列

该博客介绍了一种Java算法,用于找到给定整数数组的下一个字典序排列。当不存在更大排列时,数组将转换为升序排列。主要方法包括寻找数组中最小的比指定位置大的数并交换,然后对交换后的子数组进行升序排序。通过示例代码解释了算法的逻辑和操作步骤。

题目描述:

实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须 原地 修改,只允许使用额外常数空间。

示例 1:

输入:nums = [1,2,3]
输出:[1,3,2]
示例 2:

输入:nums = [3,2,1]
输出:[1,2,3]
示例 3:

输入:nums = [1,1,5]
输出:[1,5,1]
示例 4:

输入:nums = [1]
输出:[1]

  开始做这道题时,题目都没有看懂,着实有点菜呀!记录一下自己的做题思路

思路:可以将数组看成n位0~9的数字组成的大数,题目要求找到比这个大数大的下一个大数。

例如:1 2 3---》1 3 2

若大数已经是最大的,就找出这些数字组成的最小的数,就是升序排列  3 2 1--》1 2 3

(1)若数组大小>=2,将倒数第一个数作为起点r_max进行比较,l 指向倒数第二个数,若 l 指向的数大于倒数第二个,那么最后两位不存在更大的组合, 则将l 指向的数与倒数第一个划为一类, l--,继续查找。

(2)若l指向的数小于l+1,那么就查找划分类中最小的>l指向数组的数进行交换,最后将划分类中的数字按升序排列,跳出循环。

import java.util.*;

public class Test9 {
    public static void main(String[] args) {
       int[] nums = {5,4,7,6,2};
       nextPermutation(nums);
       for (int i=0;i<nums.length;i++){
           System.out.println(nums[i]);
       }
    }
    public static void nextPermutation(int[] nums) {
        int len = nums.length;
        if(len > 1){
            int l = len - 2;
            int r_max = len - 1;
            while (l>=0){
                if(nums[l] < nums[r_max]){
                    int less =lessMax(nums, l, r_max);
                    int temp = nums[l];
                    nums[l] = nums[less];
                    nums[less] = temp;
                    nextSort(nums, l + 1);
                    break;
                }else if(nums[l] >= nums[r_max]){
                   r_max = l;
                   l--;
                }
            }
            if(l<0){
                nextSort(nums, 0);
            }
        }
    }

    public static void nextSort(int[] nums, int l){
        for (int i=0;i<nums.length-l-1;i++){
            for (int j=l;j<nums.length -1 -i;j++){
                if(nums[j]>nums[j +1]){
                    int temp = nums[j];
                    nums[j] = nums[j +1];
                    nums[j +1] = temp;
                }
            }
        }
    }

    public static int lessMax(int[] nums, int l, int r_max){
        int less = r_max;
        int i = l +1;
        while (i<nums.length){
            if(nums[i]>nums[l]){
                if(nums[i]<nums[less]){
                    less =i;
                }
            }
            i++;
        }
        return less;
    }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值