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

题目要求:找到该排列的下一个比它大的排列。如果找不到就返回升序的排列。

思路:1.从右边第二个元素开始右到左遍历数组,找到第一个不是升序的数,记录下标i,然后再从右边第一个元素开始遍历找到第一个大于下标为i的数,记录下标为j。交换nums[i] 和 nums[j]。最后从 i + 1 到 nums.length - 1翻转数组。得到的数组就是题目要求的数组。

   2. 如果从右边第二个元素开始右到左遍历数组,找不到一个不是升序的数,则表明改排列是最大的,返回经过升序排序的数组即可或者从0到nums.length - 1翻转数组。

public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null) {
            return;
        }
        int len = nums.length;
        for (int i = len - 2; i >= 0; i--) {
            if (nums[i] < nums[i + 1]) {
                int j = 0;
                for (j = len - 1; j > i; j--) {
                    if (nums[i] < nums[j]) {
                        swap(nums, i, j);
                        reverse(nums, i + 1, len - 1);
                        return;
                    }
                }
            }
        }
        reverse(nums, 0, len - 1);
    }
    
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    private void reverse(int[] nums, int begin, int end) {
        for (int i = begin, j = end; i < j; i++, j--) {
            swap(nums, i, j);
        }
    }
}

 

posted @ 2016-03-11 08:47  YuriFLAG  阅读(156)  评论(0)    收藏  举报