zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Next Permutation

    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, do not allocate 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

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

    求出下一个排列。

    字符串的大小就是一位位去比较,下一个排列刚好比当前的排列大。

    最简单的情况是[1, 2, 3],只需要交换最后两位就得到了下一个序列。

    复杂的情况[1, 2, 4, 3],发现最后的子串[4, 3]已经是最大了的,那么需要移动一个比2大一级的数3到前面,后面子串保持递增[2, 4],结果是[1, 3, 2, 4]。

    再比如[1, 4, 7, 5, 3, 2],结果是[1, 5, 2, 3, 4, 7]

    实现的时候,先判断是不是递减序列,如果是reverse全部,

    否则先交换一位,reverse后面的子串。

     1 /**
     2  * @param {number[]} nums
     3  * @return {void} Do not return anything, modify nums in-place instead.
     4  */
     5 var nextPermutation = function(nums) {
     6     for(var i = nums.length - 1; i > 0 && nums[i] <= nums[i - 1]; i--);
     7     if(i === 0){
     8         reverse(0, nums.length - 1);
     9         return;
    10     }
    11     for(var j = i + 1; j < nums.length && nums[i - 1] < nums[j]; j++);
    12     swap(i - 1, j - 1);
    13     reverse(i, nums.length - 1);
    14     return;    
    15     
    16     function reverse(start, end){
    17         while(start < end){
    18             swap(start, end);
    19             start++;
    20             end--;
    21         }
    22     }
    23     function swap(i, j){
    24         var tmp = nums[i];
    25         nums[i] = nums[j];
    26         nums[j] = tmp;
    27     }
    28 };
  • 相关阅读:
    D django 用户认证系统
    vim 跳到指定行
    django 的auth.authenticate返回为None
    git fetch 的简单用法:更新远程代码到本地仓库
    sql语句查询出表里符合条件的第二条记录的方法
    你一定喜欢看的 Webpack 2.× 入门实战
    webpack 从入门到工程实践
    入门Webpack,看这篇就够了
    教程
    常用浏览器如何设置代理服务器上网(图文教程)
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5010337.html
Copyright © 2011-2022 走看看