題目描述:

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

解題思路:

從整個陣列的最後開始往前判斷,直到找到相鄰兩個數是增加的,記錄下這個位置為i;

如果i小於0,表示整個陣列的順序是遞減的;

從陣列的最後開始尋找,找到第一個大於nums[i]的數的位置,記為j;

交換nums[i]和nums[j]的位置,然後對i後的所有陣列進行倒序排列。

注意邊界問題,陣列不要越界。

程式碼如下:

public class Solution {
public void nextPermutation(int[] nums) {
if (nums.length < 2)
return;
int i, j, temp;
for (i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1])
break;
}
for (j = nums.length - 1; j >= 0; j--) {
if (i < 0)
break;
if (nums[j] > nums[i])
break;
}
if (i >= 0) {
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
} if (i < nums.length - 2) {
for (int k = i + 1; k <= (nums.length - i - 2) / 2 + i + 1; k++) {
temp = nums[k];
nums[k] = nums[nums.length + i - k];
nums[nums.length + i - k] = temp;
}
}
}
}