leetcode array|31. 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,31,3,2
3,2,11,2,3
1,1,51,5,1


题目的意思是要求当前排列的下一个排列,也就是将所有数进行全排列排序之后比当前排列的数值大的那一个排列,如果没有的则返回全排列的第一个。

solution中的例子:6,5,4,8,7,5,1  ——>6,5,5,1,4,7,8

从最后一个元素开始,寻找不是越来越大的一个数为4,找到它后面的值(8,7,5,1)中最小的一个 5 ,两者交换位置,将排列过的那些数进行反转,得到全排列中最小的。

自己第一次在做的时候,仅仅想到要将4和8交换位置,但这样得到的结果并不是想要的结果。

class Solution {
    public void nextPermutation(int[] nums) {
        int i=nums.length-2;
        while(i>=0&&nums[i]>=nums[i+1]){
        //while(nums[i]>=nums[i+1]&&i>=0){
            i--;
        }
        if(i>=0){
            int j=nums.length-1;
            while(j>=0&&nums[j]<=nums[i]){
                j--;
            }
            swap(i,j,nums);
        }
        reverse(i+1,nums);
    }
    
    public void reverse(int start,int[] nums){
        int i=start;
        int j=nums.length-1;
        while(i<j){
            swap(i,j,nums);
            i++;
            j--;
        }
    }
    
    private void swap(int i,int j,int[] nums){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }
}

另外,注释掉的那一行代码会造成数组越界,原因是如果那样写的话是先对数组元素进行比较再对 i 的值进行判断,与或的判断是顺序的。

猜你喜欢

转载自blog.csdn.net/xueying_2017/article/details/81081247