2.1.12 Next Permutation

Link: https://oj.leetcode.com/problems/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

我的思路:2nd time: 我知道第一步要從後往前找一個最長升序序列。在升序序列結束的下一個位置p,就是要替換的數。

e.g. 5, 3, 7, 4, 2, 1

7<-4<-2<-1是一個升序,所以換掉3。但下一步就不知道怎麼做了。

我的初始代碼:

public class Solution {
    public void nextPermutation(int[] num) {
        for(int i = num.length-2; i >=0; i--){
            if(num[i] < num[i+1]){
                int tmp = num[i];
                for(int j = i+1; j < num.length; j++){
                    if(num[j] > tmp){
                        
                    }
                }
                num[i-1] = num[i];
                num[i] = tmp;
                return;
            }
            //else continue;
        }
        
        //if the entire array is decreasing
        int l = 0;
        int h = num.length - 1;
        int tmp = 0;
        while(l < h){
            tmp = num[l];
            num[l] = num[r];
            num[r] = tmp;
            l++;
            r--;
        }
    }
}


Approach I: 正確答案:http://blog.csdn.net/linhuanmars/article/details/20434115

比如排列是(2,3,6,5,4,1): (2) 如果p存在,從p開始往後找,找到下一個比A[p]大的數字 (我的理解:實際上是找到第一個比A[p]小的數字,然後看它的前一個,也就是第一個比num[p]大的數),然後兩個調換位置,比如例子中的4。調換位置後得到(2,4,6,5,3,1)。最後把p之後的所有數字倒序,比如例子中得到(2,4,1,3,5,6), 這個即是要求的下一個排列。

這是因爲4是下一個比A[p]大的數,所以調換後,p之後的所有數一定是降序排列(6, 5, 3, 1),所以反過來即可。


Approach II: 找到p以後,數組從最後往前找,找到的第一個比num[p]大的數,就是對的。因爲num[p]以後的數遞減。

在初始代碼上改動的代碼:

public class Solution {
    public void nextPermutation(int[] num) {
        for(int i = num.length-2; i >=0; i--){
            if(num[i] < num[i+1]){
                int j = 0;
                for(j = num.length-1; j >i; j--){
                    if(num[j] > num[i]){
                        break;
                    }
                }
                int temp = num[j];
                num[j] = num[i];
                num[i] = temp;
                Arrays.sort(num, i+1, num.length);
                return;
            }
        }
        //else continue;
        //if the entire array is decreasing
        int l = 0;
        int h = num.length - 1;
        int tmp = 0;
        while(l < h){
            tmp = num[l];
            num[l] = num[h];
            num[h] = tmp;
            l++;
            h--;
        }
        return;
    }
        
}
http://blog.csdn.net/linhuanmars/article/details/20434115"最壞情況需要掃描數組三次,所以時間複雜度是O(3*n)=O(n)" //why 最壞掃三次?

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