Leetcode--Next permutation

Source: Internet
Author: User

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

Contact Us

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.