# 31. Next Permutation (Medium)

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

## Solution

1. 从后向前找到第一个顺序对 (i, i+1)
2. 从[i:]找到第一个比nums[i]大的位置j
3. 交换i，j， 排序【i+1：】

corner case:
1234,
4321

O(N) O(1)

## Code

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

if(i < 0){ // max permu
Arrays.sort(nums);
return;
}

int j = nums.length - 1;
while(nums[j] <= nums[i])
j--;

int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
Arrays.sort(nums, i+1, nums.length);
}
}
``````