1. 程式人生 > >【LeetCode】31. Next Permutation - Java實現

【LeetCode】31. Next Permutation - Java實現

文章目錄

1. 題目描述:

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

2. 思路分析:

題目的意思是給定一個數組,找出陣列中數的全排列的下一個情況,即找出下一個全排列。

下面這種演算法據說是STL中的經典演算法。在當前序列中,從尾端往前尋找兩個相鄰升序元素,升序元素對中的前一個標記為partition。然後再從尾端尋找第一個大於partition的元素,並與partition指向的元素交換,然後將partition後的元素(不包括partition指向的元素)逆序排列。比如14532,那麼升序對為45,partition指向4,由於partition之後除了5沒有比4大的數,所以45交換為54,即15432,然後將partition之後的元素逆序排列,即432排列為234,則最後輸出的next permutation為15234。確實很巧妙。

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public static void nextPermutation(int[] nums) {
    // 先從後往前找到第一次出現升序的2個數,i指向前一個數
    int i = nums.length - 2;
    while (i >= 0 && nums[i] >= nums[i + 1]) {
        i--;
    }

    // 然後從後往前找到第一個大於nums[i]的數
    if (i >= 0) {
        int j = nums.length -
1; while (nums[j] <= nums[i]) { j--; } // 交換2個下標對應的元素 swap(nums, i, j); } // 逆置i之後的所有元素 reverse(nums, i + 1); } private static void reverse(int[] nums, int start) { int i = start; int j = nums.length - 1; while (i < j) { swap(nums, i, j); i++; j--; } } private static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }