input: [1,2,3]
output:[1,3,2]
the general idea of this problem is:
iterate from end, and we need to find the first pair with nums[i - 1] < nums[i]. that means, from i to end, the array need to be decreased.
since nums[i, end] is decreased, there is no hope to increase that part. so we need to swap nums[i-1] with a number that is slightly larger than this. and clearly, we can’t swap with any value from nums[0,i-2], because if we switch with any larger number in nums[0, i-2], this actually makes the total number smaller, which is not “next permutation” we are looking for. so we need to swap nums[i-1] with nums[j] where j is from nums[i, end]. after we swap those two, the nums[i-1] increase a little, but that’s not everything, because we also need to sort everything from i to end, so that becomes ascending order. that’s how everything is down.
so take following array as example:
first we find the i-1~i pair,and we need to find j
i-1 i j
[3 7 8 5 2 4 3 2 1]
swap i-1 and j
i-1 i j
[3 7 8 5 3 4 2 2 1]
sort nums[i,j] part
[3 7 8 5 3 1 2 2 4]
and that’s done.
based on this idea, we can write following codes: (even though it could be more clearer, but still take me so many times to do it correctly, submit 15times until accepted)
class Solution {
public void nextPermutation(int[] nums) {
if(nums == null || nums.length == 0) return;
int i = nums.length - 1;
while (i > 0) {
if (nums[i - 1] < nums[i]) {
int j = nums.length - 1;
while (j >= i && nums[j] <= nums[i-1]) {
j--;
}
swap(nums, i - 1, j);
Arrays.sort(nums, i, nums.length);
return;
}
i--;
}
Arrays.sort(nums);
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}