zoukankan      html  css  js  c++  java
  • 31. Next Permutation(js)

    31. Next Permutation

    Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

    If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

    The replacement must be in-place and use only constant extra memory.

    Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

    1,2,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

    题意:找到下一组全排列

    代码如下:

    /**
     * @param {number[]} nums
     * @return {void} Do not return anything, modify nums in-place instead.
     */
    var nextPermutation = function(nums) {
            let n=nums.length;
            let i,j;
            for(  i=n-2;i>=0;i--){
    //             从后往前遍历,若后一项大于前一项时
                if(nums[i+1]>nums[i]){
                    for(  j=n-1;j>i;j--){
                        if(nums[j]>nums[i]) break;
                    }
                    swap(nums,i,j);
                    reverse(nums,i+1);
                    return;
                }
            }
            nums.reverse();
    };
    // 交换
    var swap=function(nums,i,j){
        let tmp=nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    };
    // 翻转
    var reverse=function(nums,i){
        let n=nums.length-1;
        while(i<n){
            swap(nums,i,n);
            i++;
            n--;
        }
        
    }
  • 相关阅读:
    webpack入门(1)
    react基础(2)
    react基础(1)
    react入门(5)
    react入门(4)
    react入门(3)
    webstorm出现黑色块光标
    微信小程序——组件(二)
    微信小程序——组件(一)
    react-native 在Xcode上传到iTunes Connect里报错
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10403359.html
Copyright © 2011-2022 走看看