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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
  1. find the first pair of index that n[i] < n[i+1], from the end of array.
  2. now we are sure from i+1, to the end of array, is a descending sequence, otherwise, we didn't find the correct pair in the first step.
  3. from i+1, find the largest index k, where n[k] > n[i],
  4. swap k and i, the i+1 to end still is a descending order.
  5. reverse i+1, to end.
public class Solution {
    public void nextPermutation(int[] nums) {

        int k = -1;
        for(int i =0; i< nums.length-1; i++){
            if(nums[i] < nums[i+1]) k =i; 
        }

        if(k == -1){
            reverse(nums, 0, nums.length-1);
            return;
        }

        int l = k+1;
        for(int i = k+1; i< nums.length; i++){
            if(nums[i] > nums[k]) l = i;
        }

        int tmp = nums[k];
        nums[k] = nums[l];
        nums[l] = tmp;
        reverse(nums, k+1, nums.length-1);
    }

    void reverse(int[] nums, int start, int end){
        while(start < end){
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            start++;
            end--;
        }
    }
}

results matching ""

    No results matching ""