31. 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

Analysis

link: https://leetcode.com/problems/next-permutation/discuss/13866/Share-my-O(n)-time-solution

  1. Start from the last element, traverse backward to find first number which breaks ascending order
  2. Exchange this number with the least number that’s greater than this number.
  3. Reverse sort the numbers after the exchanged number.

Solution

public void nextPermutation(int[] nums) {
    if (nums == null || nums.length < 2) {
        return;
    }
    int right = nums.length - 1; int left = right;
    while (left > 0) {
        if (nums[left] <= nums[left - 1]) {
            left--;
        } else {
            // 找到比nums[left-1]大的所以数中最小的
            while (nums[right] <= nums[left - 1]) {
                right--;
            }
            swap(nums, left - 1, right);
            // the the right index for reverseSort should be the last element in array!
            reverseSort(nums, left, nums.length - 1);
            return;
        }
    }
    int i = 0; int j = nums.length - 1;
    while (i < j) {
        swap(nums, i++, j--);
    }

}
private void reverseSort(int[] nums, int left, int right) {
    while (left < right) {
        swap(nums, left++, right--);
    }
}
private void swap(int[] array, int left, int right) {
    int temp = array[left];
    array[left] = array[right];
    array[right] = temp;
}

results matching ""

    No results matching ""