原题网址:https://leetcode.com/problems/next-permutation/
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 class Solution {
private int findChangePoint(int[] nums) {
for(int i=nums.length-2; i>=0; i--) {
if (nums[i] < nums[i+1]) return i;
}
return -1;
}
private int findLargerPoint(int[] nums, int value, int from) {
int larger = -1;
for(int i=from; i<nums.length; i++) {
if (nums[i] > value && (larger == -1 || nums[i] < nums[larger])) {
larger = i;
}
}
return larger;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void sort(int[] nums, int from, int to) {
if (from >= to || from < 0 || to >= nums.length) return;
int mid = (from+to)/2;
sort(nums, from, mid);
sort(nums, mid+1, to);
int[] merged = new int[to-from+1];
int pos = 0;
int i=from, j=mid+1;
while (i<=mid || j<=to) {
if (i>mid) merged[pos++]=nums[j++];
else if (j>to) merged[pos++]=nums[i++];
else if (nums[i]<=nums[j]) merged[pos++]=nums[i++];
else merged[pos++]=nums[j++];
}
for(int k=from; k<=to; k++) nums[k]=merged[k-from];
}
public void nextPermutation(int[] nums) {
int change = findChangePoint(nums);
if (change >= 0) {
int larger = findLargerPoint(nums, nums[change], change + 1);
swap(nums, change, larger);
}
sort(nums, change+1, nums.length-1);
}
}