Next Permutation

来源:互联网 发布:手机淘宝国际版 编辑:程序博客网 时间:2024/06/05 09:54

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, do not allocate 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

Example : 6, 8, 9, 5,4,3,2

1. From right to left, find the first element that is not in an ascending order. In this example, the element is 8.

2. Form right to left, find the first element that is bigger than the element we found in step 1. In this example, it is 9. Swap these two numbers.  

6,8,9,5,4,3,2 -> 6,9,8,5,4,3,2

3.Reverse the list from the next index of the number found in step 1. 

6,9,8,5,4,3,2 -> 6,9,2,3,4,5,8

Special Example: 5,4,3,2,1

The next permutation should be 1,2,3,4,5

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



0 0
原创粉丝点击