31. 下一个排列 Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

Input: nums = [1,2,3]
Output: [1,3,2]

 

方法:

1.从右往左找第一组相邻的num[i]<nums[i+1]数

2.从右往左找第一个大于num[i]的数j

3.交换i和j

4.i之后的数重新从小到大排序

 

public void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        while( i >=0 && nums[i] >= nums[i + 1]) i--;
        if (i >=0 ){
            int j = nums.length - 1;
            while (j >= 0 && nums[i] >= nums[j]) j--;
            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 left = start, right = nums.length - 1;
        while (left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }

 

参考链接:

https://leetcode.com/problems/next-permutation/

https://leetcode-cn.com/problems/next-permutation

posted @ 2020-12-14 17:23  diameter  阅读(68)  评论(0编辑  收藏  举报