Description:
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.
Solution:
这里我们可以假设有这么几个数字:d c b a
先忽略相等的情况,那么可以发现
if a > b
then switch a, b
else // (a<b)
if b > c
then b,a,c (a<c) or b,c,a (c<a)
else // a<b<c
then ...
综上就是这么几个结论:
找到从后往前第一个增长的点,假设增长的点位ascendingPoint,简称ap。(这里因为代码方便,我设置的是ap-1,ap是增长两个前后点)。
那么需要把所有[ap,length()-1]的点中找到比ap-1点的数值大的 最小值(大于ap-1的最小点),这个最小点就是变换之后在ap-1这个位置的数值,后面的排序即可。
如果ap=0,就表示所有的点递减,那么按照题目要求重新排序就好。
import java.util.Arrays;
public class Solution {
public void nextPermutation(int[] nums) {
int ascendingPoint = getAscendingPoint(nums);
if (ascendingPoint == 0) {
Arrays.sort(nums);
} else {
int minBigger = Integer.MAX_VALUE;
for (int i = nums.length - 1; i >= ascendingPoint; i--) {
if (nums[i] > nums[ascendingPoint - 1] && nums[i] < minBigger) {
minBigger = nums[i];
nums[i] = nums[ascendingPoint - 1];
nums[ascendingPoint - 1] = minBigger;
}
}
Arrays.sort(nums, ascendingPoint, nums.length);
}
}
int getAscendingPoint(int nums[]) {
for (int i = nums.length - 1; i > 0; i--)
if (nums[i] > nums[i - 1])
return i;
return 0;
}
}