Next Permutation

2018-09-21  本文已影响0人  BLUE_fdf9

题目
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

答案

class Solution {
    public void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    public void reverse(int[] nums, int l, int r) {
        while(l < r) swap(nums, l++, r--);
    }
    
    public void nextPermutation(int[] nums) {
        int n = nums.length;
        int p = -1, c = -1;
        for(int i = n - 1; i > 0; i--) {
            if(nums[i] > nums[i - 1]) {
                p = i - 1;
                break;
            }
        }
        if(p == -1) {
            reverse(nums, 0, nums.length - 1);
            return;
        }
        for(int i = n - 1; i > p; i--) {
            if(nums[i] > nums[p]) {
                c = i;
                break;
            }
        }
        swap(nums, p, c);
        reverse(nums, p + 1, nums.length - 1);
    }
}
上一篇下一篇

猜你喜欢

热点阅读