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, 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
public void nextPermutation(int[] nums) {
int i;
for (i = nums.length - 1; i > 0; --i)
if (nums[i] > nums[i - 1])
break;
if (i > 0)
for (int j = nums.length - 1; j >= i; --j)
if (nums[j] > nums[i - 1]) {
swap(nums, j, i - 1);
break;
}
reverse(nums, i, nums.length - 1);
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private static void reverse(int[] nums, int i, int j) {
while (i < j)
swap(nums, i++, j--);
}
思路:找下一个排列中略大于现在数的数。如果这个数存在,则数组中一定有一个低位数大于某一高位数。从个位开始向高位逐一查找,看相邻两数是否高位的较小(注意相邻两数的关系已经决定了数列的单调性),如果是,那么需要找一个大于它的数和它置换。可以证明高位之后的数字是递减排列,所以从最低位找到第一个大于该高位的数与之置换,则新数一定大于当前数,且该高位后为递减排列,这时需要把这部分倒置为递增排列。如果这个数不存在,可以证明,整个数组是递减排列,整体倒置即可。