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

尋找下一個全排列問題,比如題中的1,2,3
全排列是:
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
比1,2,3大的並且按照字典序最小的排列是1,3,2。
而如果是3,2,1,那麼輸出最下字典序排列1,2,3。


暴力方法是尋找出所有的全排列,那麼就是一個回溯問題,複雜度普遍是O(n!)。而這道題目是可以通過O(n)解決的。
1、從後向前依次比較兩個相鄰的元素,可以記第一個爲first,第二個爲second。知道first

public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums.length <= 1) return;
        int i = nums.length-2;
        //比較相鄰兩個元素,第一個元素小於第二個跳出循環。
        while (i>=0 && nums[i] >= nums[i+1])i--;
        if (i >= 0) {
            //如果找到第一個元素,再次從後遍歷,找到一個比第一個元素大的元素跳出循環。
            int j = nums.length - 1;
            while (nums[i] >= nums[j]) j--;
            swap(nums,i,j);
        }
        //第一個元素後的元素是遞減的,翻轉即可
        reverse(nums,i+1,nums.length - 1);
    }

    public void swap(int[] A, int i, int j) {
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }

    public void reverse(int[] A, int i, int j) {
        while(i < j) swap(A, i++, j--);
    }

}
發佈了57 篇原創文章 · 獲贊 21 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章