leetcode 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 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

中文理解:

给出一个数组,给出数组组成的所有数排列中当前数组的下一个序列。

解题思路:

根据规律:比如1 2 7 4 3 1数列的下一个序列是1 3 1 2 4 7,首先从原始序列尾部开始找到第一个不符合升序的数字2,然后从尾部开始找到升序序列中第一个比2大的数字3,调换2,3,得到1 3 7 4 2 1,然后将3后面的序列逆转即可得到1 3 1 2 4 7结果。

代码(java):

class Solution {
    public void nextPermutation(int[] nums) {
        //从后面找到第一个逆序的
        int i=0,j=0;
        for(i=nums.length-1;i>0;i--){
            if(nums[i]>nums[i-1])break;
        }
        //得到逆序的下标
        i--;
        if(i==-1){
            reverse(nums,0);
            return;
        }
        //获得从后向前第一个比nums[i]大的数字
        for(j=nums.length-1;j>i;j--){
            if(nums[j]>nums[i])break;
        }
        swap(nums,i,j);
        reverse(nums,i+1);
    }
    public void swap(int[]nums,int i,int j){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }
    public void reverse(int[] nums,int start){
        int len=nums.length-1;
        while(start<len){
            swap(nums,start,len);
            start++;
            len--;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/90028318