Next permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must is in-place, do not allocate extra memory.
Here is some examples. Inputs is in the left-hand column and its corresponding outputs is in the right-hand column.
1,2,3→1,3,2
3,2,1→1,2,3
1,1,5→1,5,1
Idea: This is the leetcode I have done at the moment, it is difficult to find that the algorithm is very difficult to achieve their own short time, assuming that once did not do this problem, almost very difficult to have a very quick idea to solve the problem.
I also tried several solutions before I took the online data. But no one can achieve the effect. Final reference information. Just suddenly: This can also do this, but my concubine very difficult to think Ah!
The general idea of the topic is. Read forward from the back. When the number of subsequent numbers is larger than the previous number, a loop is opened, starting from the back to the current number comparison. When it is larger than the current number, swap. Then start from the last one in the current number until the final reverse order is available.
Detailed code and gaze such as the following:
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]) {//assuming nums[i] > nums[i-1 ]//again from the forward to infer if there is no number than nums[i-1] large int j = nums.length-1; for (; J >= i-1;j--) {if (Nums[j] > Nums[i-1]) {break;//If any, the loop ends. Keep J's Value}}//Will nums[j] and nums[i-1] Exchange int temp = Nums[j]; NUMS[J] = nums[i-1]; NUMS[I-1] = temp; From I start the reverse order (that is, where the swap position begins to reverse) 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; }}//Assuming that there is no data exchanged at the end, the description is in descending order and needs to be arranged in ascending order for (int i = 0; i< nums.length/2;i++) {int J = nums.length-1-i;//double pointer sort, Exchange echoes 22 data can be int temp = nums[i]; Nums[i] = Nums[j]; NUMS[J] = temp; } }}
Leetcode 31.Next permutation (next dictionary ordering) thinking and method of solving problems