Skip to content

Latest commit

 

History

History
46 lines (40 loc) · 1.25 KB

31. 下一个排列.md

File metadata and controls

46 lines (40 loc) · 1.25 KB

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。

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

solution:

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function(nums) {
    if (nums.length > 1) {
        let i = nums.length - 1
        let key, idx
        let revArr
        while(nums[i - 1] >= nums[i]) {
            i--
        }
        if (i === 0) {
            revArr = nums.splice(0, nums.length).reverse()
        } else {
            idx = i - 1
            key = nums[i - 1]
            while(nums[i] > key && nums[i + 1] > key && i < nums.length - 1) {
                i++
            }
            [nums[idx], nums[i]] = [nums[i], nums[idx]]
            revArr = nums.splice(idx + 1, nums.length - idx - 1).reverse()
        }
        while(revArr.length) {
            nums.push(revArr.shift())
        }
    }
};