leetcode-31

 

Achieve a function of the acquired arrangement, a given algorithm requires rearranging the sequence number next in lexicographically larger arrangement.

If the next larger arrangement does not exist, the smallest number of rearranged alignment (i.e., ascending order).

You must place editing, allowing only constant additional space.

The following are some examples, the input column on the left, on the right column the corresponding output.
→ 1, 3,2, 2, 3
3,2,1 →, 2, 3
1,1,5 1,5,1 →

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/next-permutation
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

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

    private void reverse(int[] nums, int start) {
        int i = start, j = nums.length - 1;
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

 

First is to select a high need to swap, this into a high position since it is greater than right from the upper (rear) and the minimum number of

Then because the process before we have to ensure that an "orderly tail", the exchange of quick manner so that the tail becomes a descending order from left to right,

 

This question is not difficult to analyze, a common problem in mathematics.

Guess you like

Origin www.cnblogs.com/CherryTab/p/12189727.html