Skip to main content

Command Palette

Search for a command to run...

LeetCode Solution, Medium, 31. Next Permutation

下一個排序

Published

I am not a programmer just a leaner. Writing JavaScript, Python, and Go and doing something on Kubernetes.

31. Next Permutation

題目敘述

A permutation of an array of integers is an arrangement of its members into a sequence or linear order.

  • For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1].

The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

  • For example, the next permutation of arr = [1,2,3] is [1,3,2].
  • Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
  • While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.

Given an array of integers nums, find the next permutation of nums.

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

Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]

Example 2:

Input: nums = [3,2,1]
Output: [1,2,3]

Example 3:

Input: nums = [1,1,5]
Output: [1,5,1]

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

題目翻譯

給一個整數陣列 nums,需要找出此排序之後的下一個大的排序。如果已經是最大的排序的話就升序輸出。

解法解析

  1. 從結尾往開頭尋找,找到第一個降冪的值 x
  2. 從第一步找到的值 x 的位置到結尾的這段資料中,找到大於 x 中的最小值 y (例如 x = 4, x-> n-1 中有 5, 6, 9,則選擇 5)
  3. xy 的位置互換
  4. x-> n-1 的值做從小到大排序

解法範例

Go

func nextPermutation(nums []int) {
    nlen := len(nums)
    if nlen <= 1 {
        return
    }

    for i := nlen - 1; i > 0; i-- {
        if nums[i] <= nums[i-1] {
            continue
        }

        j := i
        for ; j < nlen-1; j++ {
            if nums[j] > nums[i-1] && nums[j+1] <= nums[i-1] {
                break
            }
        }

        nums[i-1], nums[j] = nums[j], nums[i-1]
        reverse(nums[i:])
        return
    }

    // in case an arrangement is impossible
    reverse(nums)
}

func reverse(nums []int) {
    for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
        nums[i], nums[j] = nums[j], nums[i]
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function (nums) {
    function swap(i, j) {
        const temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

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

    let i = nums.length - 2;
    while (i >= 0 && nums[i + 1] <= nums[i]) {
        i--;
    }

    if (i >= 0) {
        let j = nums.length - 1;
        while (j >= 0 && nums[j] <= nums[i]) {
            j--;
        }
        swap(i, j);
    }
    reverse(i + 1);
};

Kotlin

class Solution {
    fun nextPermutation(nums: IntArray) {
        var i = nums.size - 2

        while (i >= 0 && nums[i + 1] <= nums[i]) {
            i--
        }

        if (i >= 0) {
            var j = nums.size - 1
            while (j >= 0 && nums[j] <= nums[i]) {
                j--
            }
            swap(nums, i, j)
        }
        reverse(nums, i + 1)
    }

    fun swap(nums: IntArray, i: Int, j: Int) {
        val temp = nums[i]
        nums[i] = nums[j]
        nums[j] = temp
    }

    fun reverse(nums: IntArray, i: Int) {
        var left = i
        var right = nums.size - 1
        while (left < right) {
            swap(nums, left, right)
            left++
            right--
        }
    }
}

PHP

class Solution
{

    /**
     * @param Integer[] $nums
     * @return NULL
     */
    function nextPermutation(&$nums)
    {
        $length = count($nums);
        $i = $length - 2;
        while ($i >= 0 && $nums[$i] >= $nums[$i + 1]) {
            $i--;
        }
        if ($i >= 0) {
            $j = $length - 1;
            while ($nums[$i] >= $nums[$j]) {
                $j--;
            }
            [$nums[$i], $nums[$j]] = [$nums[$j], $nums[$i]];
        }

        $revStart = $i + 1;
        $revEnd = $length - 1;
        while ($revStart < $revEnd) {
            [$nums[$revStart], $nums[$revEnd]] = [$nums[$revEnd], $nums[$revStart]];
            $revStart++;
            $revEnd--;
        }
    }
}

Python

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i = len(nums) - 2
        while i >= 0 and nums[i] >= nums[i + 1]:
            i -= 1
        if i >= 0:
            j = len(nums) - 1
            while nums[i] >= nums[j]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]

        rev_start = i + 1
        rev_end = len(nums) - 1
        while rev_start < rev_end:
            nums[rev_start], nums[rev_end] = nums[rev_end], nums[rev_start]
            rev_start += 1
            rev_end -= 1

Rust


Swift

class Solution {
  func reverse(_ nums: inout [Int], _ left: Int, _ right: Int) {
    var left = left
    var right = right

    while left < right {
      nums.swapAt(left, right)
      left += 1
      right -= 1
    }
  }

  func nextPermutation(_ nums: inout [Int]) {
    guard nums.count > 1 else {
      return
    }

    var idx1 = nums.count - 2
    while idx1 >= 0 && nums[idx1] >= nums[idx1 + 1] {
      idx1 -= 1
    }

    if idx1 >= 0 {
      var idx2 = nums.count - 1
      while idx2 >= 0 && nums[idx2] <= nums[idx1] {
        idx2 -= 1
      }
      nums.swapAt(idx1, idx2)
    }
    reverse(&nums, idx1 + 1, nums.count - 1)
  }
}

LeetCode Solution

Part 1 of 50

A collection of leetcode solustion

More from this blog

如何開始入門軟體工程領域 - 名詞解釋(長期更新)

現在應該開始有很多人想要踏入軟體工程的領域,但在進入這個領域之前,覺得先了解一些名詞,可以在入門時更有方向也更知道要用什麼關鍵字去找尋有用的資訊。這篇文章就是想要幫助想要入門的人理解一些軟體工程裡的專有名詞。 作業系統 這一區塊主要解釋跟作業系統層面相關的名詞 英文中文解釋 Operation system 簡稱 OS | 作業系統 | 就是電腦的作業系統,是三大作業系統分別是:Linux、Windows、macOS | | Linux | | 自由和開放原始碼的 UNI...

May 10, 2023

我的 MacBook Pro (Apple Silicon) 設定

現在開始因為 ChatGPT 的出現,各種 AI 助手的功能都跑出來了。想想自己用了許久的環境設定也應該要來重新審視和建立新的開發環境了,僅此紀錄我個人的環境配置步驟和設定。 環境前置步驟 還原 MacBook Pro 至全新環境 macOS(全部資料刪除) 設定好初始設定後,登入 Apple ID 進入 App Store 確定 macOS 版本和預設 APP 都更新到最新 macOS 版本 到系統設定調整所有設定至個人習慣的設定 三指拖移 觸控板手勢開啟 防火牆開啟 輸入法設定...

Apr 25, 2023

ChatGPT 下的發展預想

從 ChatGPT 問世到現在,有許許多多的文章和討論出來。先從最早的 Google 要完蛋了,到後來的工作要被取代了,工程師失業了。 我就比較沒有想要馬上出來評論一下,我喜歡讓子彈飛一會兒。跟討論一下我自己比較在意的討論點。 Google 為什麼慢了? 結論:因為他需要更小心 很多人說 Google 怎麼被微軟搶先了一步。剛開始 Bing 說要加上 AI 的時候大家都在說 Google 怎麼慢了。我就馬上跑去看 OpenAI 的網站,靠北呀啊就 Azure 贊助的。那當然在正式上線 ChatG...

Mar 23, 2023

不工程的攻城獅

223 posts

I am not a programmer because I am not good at programming. But I do programming. Love to learn new things. An animal lover and a dancer. My oshi is 潤羽るしあ.

LeetCode Solution, Medium, 31. Next Permutation