LeetCode第31题 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 and use only constant 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 NextPermutation{
public static void main(String[] args){
int[] nums = {3,2,1};
NextPermutation np = new NextPermutation();
np.nextPermutation(nums);
for(Integer temp : nums){
System.out.println(temp);
}
}
/*
将数组中的数重新排序,获得一个比当前数大的排序后最小数
若这样的数不存在,则将数值中的数,按升序排序
要使尽可能第的位变大,这样就可以使得获得的数尽可能小,所以从最低位开始进行放大操作
放大操作是基于交换操作
若是与交换位的左边进行交换不一定获得符合要求的数:158 4 76531 -> 458 1 76531、148 5 76531
若是与交换位的右边进行交换获得符合要求的数:158 4 76531 -> 158 5 76431(刚好)、158 6 74531(太大)、158 3 76541(变小)
158 5 76431(刚好) -> 158 5 13567
总结:从十位寻找合适的交换位(即不再升序的位),在交换位之前寻找比他大的最小数,将这两个数进行交换,将交换位之前的数逆序
*/
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
//找到第一个不再递增的位置
while (i >= 0 && nums[i + 1] <= nums[i]) {
i--;
}
//如果到了最左边,就直接倒置输出
if (i < 0) {
reverse(nums, 0);
return;
}
//找到刚好大于 nums[i]的位置
int j = nums.length - 1;
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
//交换
swap(nums, i, j);
//利用倒置进行排序
reverse(nums, i + 1);
}
private void swap(int[] nums, int i, int j) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
private void reverse(int[] nums, int start) {
int i = start, j = nums.length - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
}