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
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
思路:此题是我眼下做过的leetCode中感觉最难的题,它的难在于算法非常难自己短时间实现,假设曾经没有做过这种题,差点儿非常难非常快的有思路解出来。
在參考网上资料之前,我也尝试了好几种解法。可是没有一种能达到效果。最后參考资料。才恍然:这尼玛也能够这样做,可是臣妾非常难想到啊!
题目的总体思路是。从后往前读。当后面的数比前面的数大时,在开一个循环,从后開始于当前数比較。当比当前数大时,交换。然后再从当前数的后一位開始,直到最后反序就可以。
详细代码和凝视例如以下:
public class Solution { public void nextPermutation(int[] nums) { if(nums.length <= 1){ return; } for(int i = nums.length - 1;i > 0; i--){ if(nums[i] > nums[i-1]){//假设nums[i] > nums[i-1] //再从后往前推断有否数字比nums[i-1]大 int j = nums.length - 1; for(; j >= i -1;j--){ if(nums[j] > nums[i-1]){ break;//如有,则结束循环。保留j的值 } } //将nums[j]和nums[i-1]交换 int temp = nums[j]; nums[j] = nums[i-1]; nums[i-1] = temp; //从i開始反序(即交换位置的地方開始反序) for(j = 0; j < (nums.length - (i))/2;j++){ int k = nums.length - 1 - j; int m = nums[j+i]; nums[j+i] = nums[k]; nums[k] = m; } return; } } //假设到最后没有交换的数据,则说明是降序排列,须要升序排列 for(int i = 0; i < nums.length/2;i++){ int j = nums.length - 1 - i;//双指针排序,交换首尾相应的两两数据就可以 int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } }