lintcode :Permutation Index 排列序號


題目:

給出一個不含重復數字的排列,求這些數字的所有排列按字典序排序后該排列的編號。其中,編號從1開始。

樣例

例如,排列[1,2,4]是第1個排列。

解題:

這個題目感覺很坑的。感覺這只有求出所有的排列,然后找出其對應的下標,但是怎么求出排列,在做Project Euler 時候碰到過,但是現在我又不會寫了,那時候畢竟是抄別人的程序的。在geekviewpoint看到一種很厲害的解法,不需要求所有的排列,直接根據給的數組進行求解。

思路:

1.對於四位數:4213 = 4*100+2*100+1*10+3

2.4個數的排列有4!種。當我們知道第一位數的時候,還有3!種方式,當知道第二位數時候還有2!種方式,當知道第三位數的時候還有1!種方式,前面三位數都確定的時候,最后一位也確定了。<這里是按照高位到地位的順序>

3.對4個數的排列,各位的權值為:3!,2!,1!,0!。第一位之后的數小於第一位的個數是x,第二位之后的數小於第二位的個數是y,第三位之后的數小於第三的個數是z,第四位之后的數小於第四位的個數是w,則abcd排列所在的序列號:index = x*3!+y*2!+z*1!,<0!=0>

在數的排列中,小數在前面,大數在后面,所以考慮該位數之后的數小於該為的數的個數,這里我自己理解的也不是很透,就這樣。

4.例如 4213;x= 3,y = 1,z=0,index = 18+2=20

123;x = 0,y=0,index = 0

321;x= 2,y=1,index = 2*2!+1*1! = 5

這里的下標是從0開始的。

Java程序:

public class Solution {
    /**
     * @param A an integer array
     * @return a long integer
     */
    public long permutationIndex(int[] permutation) {
        // Write your code here
    long index = 0;
    long position = 2;// position 1 is paired with factor 0 and so is skipped
    long factor = 1;
    for (int p = permutation.length - 2; p >= 0; p--) {
        long successors = 0;
        for (int q = p + 1; q < permutation.length; q++) {
            if (permutation[p] > permutation[q]) {
                successors++;
            }
        }
    index += (successors * factor);
    factor *= position;
    position++;
    }
    index = index + 1;
    return index;
    }
}
View Code

總耗時: 5756 ms

Python程序:

class Solution:
    # @param {int[]} nums an integer array
    # @return {long} a long integer
    def permutationIndex(self, nums):
        # Write your code here
        index = 0
        position  = 2 
        factor = 1 
        numslen = len(nums)
        for i in range((numslen-2),-1,-1):
            successors = 0
            for j in range((i+1),numslen):
                if nums[i]>nums[j]:
                    successors+=1
            index += successors*factor
            factor*=position
            position+=1
        index +=1
        return index
View Code

總耗時: 223 ms

同時,九章上面的程序還看不懂。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM