27.Next Permutation(下一个字典序列)

Level:

  Medium

题目描述:

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 and use only constant 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

思路分析:

  这道题要求是给出当前序列的下一个序列(当前序列的下一个更大的序列),意思就是求当前序列的下一个字典序列。那么我们有以下算法:

  给定一个序列假如是a1,a2,a3,..ai,ai+1,ai+2..,aj..an
  1.找到最后一个正序序列ai,ai+1;
  2.找到ai后面最后一个比他大的数aj;
  3.交换ai和aj; a1,a2,a3,..aj,ai+1,ai+2..,ai..an
  4.将aj后面的所有数反转,即得到下一个序列,即下一个比它大的数

代码:

public class Solution{
    public void nextPermutation(int []nums){
        if(nums==null||nums.length==0)
            return;
        //第一步找到最后一对正序序列
        int flag=-1;
        for(int i=nums.length-1;i>=1;i--){
            if(nums[i]>nums[i-1]){
                flag=i-1;
                break;
            }
        }
       // 如果不存在正序,则证明该序列是由大到小的逆序,则反转整个序列
        if(flag==-1){
            reverse(nums,flag+1,nums.length-1);
            return;
        }
        //如果存在正序,则找到flag后面最后一个比它大的数,并交换
        for(int j=nums.length-1;j>flag;j--){
            if(nums[j]>nums[flag]){
                int temp=nums[j];
                nums[j]=nums[flag];
                nums[flag]=temp;
                break;
            }
        }
       //反转flag位置后的序列
        reverse(nums,flag+1,nums.length-1);
        return ;
        }
    public void reverse(int []nums,int start,int end){//反转序列
        while(start<end){
            int temp=nums[end];
            nums[end]=nums[start];
            nums[start]=temp;
            start++;
            end--;
        }
    }
}
原文地址:https://www.cnblogs.com/yjxyy/p/10772963.html