Leetcode #31. Next Permutation 下一个全排列 解题报告

1 解题思想

这道题是给定一个排序,让你找出使用字典序的方式排序后得到的下一个全排列
什么是字典序排序?

字典排序(lexicographical
order)是一种对于随机变量形成序列的排序方法。其方法是,按照字母顺序,或者数字小大顺序,由小到大的形成序列。

其实也就是将全排列按照字典序的方式,得到一个递增的序列。

那么我们如何确定下一个字典序?

做法,对于当前序列有:
1、找到从右边(末尾)开始的第一个数pi,pi正好小于他的后一位,p(i)小于p(i+1),即pi和p(i+1)是顺序的

2、找到这个数pi之后(向右)的,大于他的,且是大于他里面最小的pj,最靠后的哪一个位置(即大于数pi的最小的里面且最靠右的那一个)
3、交换pi pj
4、将位置从i+1到末尾结束的数字全部颠倒

那么每一次变换的方式就如上了,如果哪一步执行不了了,那么就证明已经排序完成

2 原题

https://leetcode.com/problems/next-permutation/
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

3 AC解

public class Solution {
    //字典序排序
    public void swap(int[] nums,int a,int b){
        int tmp=nums[a];
        nums[a]=nums[b];
        nums[b]=tmp;
    }
    public void nextPermutation(int[] nums) {
        if(nums.length<2)
            return ;
        int i,j;
        //找到从右边开始的第一个顺序的数字,及第一个数pi,p(i)<p(i+1)
        i=nums.length-2;
        while(i>=0 && nums[i]>=nums[i+1])
            i--;
        //找不到的话就根据题目意思排序结束。
        if(i<0){
            Arrays.sort(nums);
            return ;
        }
        //找到这个数之后的,大于他的,且是大于他里面最小的,最靠后的哪一个位置
        int max=Integer.MAX_VALUE,index=nums.length;
        for(j=i+1;j<nums.length;j++){
            if(nums[j]>nums[i] && nums[j]<=max){
                max=nums[j];
                index=j;
            }
        }
       if(index>=nums.length)
            return;
      //交换
       swap(nums,i,index);
       //同时颠倒i+1之后的程序
       i++;
       j=nums.length-1;
       while(i<j){
           swap(nums,i++,j--);
       }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值