问题描述:
Implementnext permutation, which rearranges numbers into the lexicographically nextgreater permutation of numbers.
Ifsuch arrangement is not possible, it must rearrange it as the lowest possibleorder (ie, sorted in ascending order).
Thereplacement must be in-place, do not allocate extra memory.
Hereare some examples. Inputs are in the left-hand column and its correspondingoutputs are in the right-hand column.1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
问题分析:
列举一个例子:1,1,5,7,6,4,3,1其下一个数是1, 1,6,1,3,4,5,7
可以看到5和6调换了顺序,然后6之后的数组{7,5,4,3,1}然后再逆序即可得到结果;
之所调换5和6,是从后往前遍历数组,直至发现第一个nums[i] < nums[i + 1]的位置i;然后交换nums[i]与i之后数组中的最小值nums[j];
再反转i+1到末位的数组即可。
代码:
public class Solution {
public void nextPermutation(int[] nums) {
if (nums.length <= 1)
return;
// 找到第一个nums[i] < nums[i +1]的位置i;注意从后往前寻找
int i = nums.length - 2;
while ((i >= 0) && (nums[i] >=nums[i + 1]))
i--;
// 如果上述情况存在,则表示有下一个更大值
if (i >= 0) {
// 找到i位置后大于nums[i]的最小值nums[j],然后交换nums[i]与nums[j]
// 根据前面遍历性质知后面i后的数组肯定是降序排列的,故找最小值仅需要从末位开始比较就可
int j = nums.length - 1;
while (nums[i] >= nums[j])
j--;
exchange(nums, i, j);
}
// 再反转i到末尾所有元素值,这里采用双指针法反转
for (int start = i + 1, end = nums.length - 1; start < end; start++, end-- )
exchange(nums, start,end);
}
// 交换数组内两个位置数据
private void exchange(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}