Leetcode-Next Permutation(Java)

Question:

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

Thinking:

The method can be described as below:

Solution:

public void nextPermutation(int[] nums) {
    if (nums == null || nums.length == 0)
        return;
    int i = nums.length - 2;
    while (i >= 0 && nums[i] >= nums[i+1]){
        i--;
    }

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

    int j = i+1;
    while (j < nums.length && nums[j] > nums[i]){
        j++;
    }
    j--;
    swap(nums, i, j);
    reverse(nums, i+1, nums.length-1);

    return;
}
private void swap(int[] nums, int i, int j){
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}
private void reverse(int[] nums, int i, int j){
    while (i < j){
        swap(nums, i++, j--);
    }
}

Reference:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html
http://www.cnblogs.com/springfor/p/3896245.html