0
点赞
收藏
分享

微信扫一扫

数据结构与算法之LeetCode-31-下一个排列(使用字典序,什么是字典序)

A邱凌 2022-03-13 阅读 113

31. 下一个排列 - 力扣(LeetCode) (leetcode-cn.com)

字典序(dictionary order),又称 字母序(alphabetical order),原意是表示英文单词在字典中的先后顺序,在计算机领域中扩展成两个任意字符串的大小关系。

img

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function(nums) {
  let i = nums.length - 2;
  while(i>=0&&nums[i]>=nums[i+1]){
    i--;
  }
  if(i>=0){
    let j = nums.length-1;
    while(j>=0&&nums[i]>=nums[j]){
      j--;
    }
    swap(nums,i,j);
  }
  reverse(nums,i+1);
};

var swap = function(nums,i,j){
  let temp = nums[i];
  nums[i] = nums[j];
  nums[j] = temp;
}

var reverse = function(nums,start){
  let left = start, right = nums.length-1;
  while(left<right){
    swap(nums,left,right);
    left++;
    right--;
  }
}

参考链接

31. 下一个排列 - 力扣(LeetCode) (leetcode-cn.com)

字典序_雪雪-CSDN博客_字典序

下一个排列 - 下一个排列 - 力扣(LeetCode) (leetcode-cn.com)

下一个排列算法详解:思路+推导+步骤,看不懂算我输! - 下一个排列 - 力扣(LeetCode) (leetcode-cn.com)

举报

相关推荐

0 条评论