Title Description:
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
Given a sequence, find the next sort.
Ideas:
Will index, INDEX2 =-1;
1. From right to left, if not satisfied num[i+1] < num [I],index = i;
2. Then find the number of the first num[i] > Num[index] from right to left, index 2 = i;
3. Exchange Num[index] and NUM[INDEX2]
4. Reverse the number of num[index+1. N].
Implementation code:
public class Solution {public void Nextpermutation (int[] nums) { var index =-1; for (var i = nums. Length-1; i > 0; i--) { if (Nums[i] > Nums[i-1]) { index = i-1; break; } } var index2 =-1; if (Index! =-1) {for (var i = nums. Length-1; I >= 0; i--) { if (Nums[i] > Nums[index]) { index2 = i; Break ; }}} if (Index! =-1 && index2! =-1) { var t = Nums[index]; Nums[index] = Nums[index2]; NUMS[INDEX2] = t; } var k = index + 1; var j = Nums. Length-1; while (K < j) { var tmp = nums[k]; NUMS[K] = nums[j]; NUMS[J] = tmp; k++; j--;}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Next permutation