This is a creation in Article, where the information may have evolved or changed.
# #31. Next permutation
Title: 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.
Translate: Implement the next arrangement and rearrange the numbers into the next larger arrangement of numbers. If this arrangement is not possible, it must be rearranged to the lowest possible order (that is, in ascending sort). Replace must be in the original location, do not allocate additional memory.
Thinking: The test instructions of this problem is more obscure ah, the internet to find someone else's example to understand the meaning of the topic .... , know the meaning of the topic, the problem is a lot easier. Test instructions: It is the combination of each element of the array into a number, such as [1,3,1,3,1], then 13131, and then with the elements in the array to rearrange, get a bit larger than 13131, that is, 13311, the answer is it.
Implementation process:
1. To iterate through the array, if Nums[i-1]<nums[i], then i-1 the position need to change the value, we set index=i-12. And then again in reverse, if you find Nums[i]>nums[index], swap two numbers, and the index subscript after the number in ascending order to get the answer.
3. The title also requires no more than the original value of the next arrangement, you need to put the original sequence in ascending order, that is, 3,2,1, no larger than his number, you need to return to the three
Here is the code implementation:
Golang Code:
Package Main import ("FMT") func main () {nums: = []int{1, 2} nextpermutation (Nums) Fmt. Println (Nums)} func nextpermutation (Nums []int) {arrlen: = Len (nums) if Arrlen < 2 {return} in Dex: =-1 for i: = arrLen-1; i > 0; i--{if nums[i-1] < Nums[i] {index = i-1 break}} If Index = =-1 { Reserve (Nums) return} for I: = arrLen-1; i > 0; i--{if nums[i] > Nums[index] {nums[i], nums[index] = Nums[index], Nums[i] Reserve (nums[ Index+1:]) Break}} return} Func reserve (Nums []int) {for I, J: = 0, Len (nums)-1; i < J I, j = i+1, j-1 {nums[i], nums[j] = Nums[j], Nums[i]} return}