# [Leetcode] [JavaScript] Next permutation

Source: Internet
Author: User

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`

https://leetcode.com/problems/next-permutation/

Find the next arrangement.

The size of the string is a bit to compare, the next arrangement is just larger than the current arrangement.

The simplest case is [1, 2, 3], and only the last two bits are exchanged to get the next sequence.

The complex case [1, 2, 4, 3], found that the last substring [4, 3] is already the largest, then need to move a number 2 to the front, and the back substring to be incremented [3, 2], the result is [4, 1, 3, 2].

Again such as [1, 4, 7, 5, 3, 2], the result is [1, 5, 2, 3, 4, 7]

The realization of the time, first judge is not descending sequence, if it is reverse all,

Otherwise, first swap one bit, reverse the back of the substring.

`1 /**2 * @param {number[]} nums3 * @return {void} does not return anything, modify Nums in-place instead.4  */5 varNextpermutation =function(nums) {6      for(vari = nums.length-1; I > 0 && nums[i] <= nums[i-1]; i--);7     if(i = = 0){8Reverse (0, Nums.length-1);9         return;Ten     } One      for(varj = i + 1; J < Nums.length && Nums[i-1] < nums[j]; J + +); ASwap (i-1, j-1); -Reverse (i, nums.length-1); -     return;  the      -     functionreverse (start, end) { -          while(Start <end) { - swap (start, end); +start++; -end--; +         } A     } at     functionSwap (I, j) { -         varTMP =Nums[i]; -Nums[i] =Nums[j]; -NUMS[J] =tmp; -     } -};`

[Leetcode] [JavaScript] Next permutation

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.