lintcode197- Permutation Index- easy

Given a permutation which contains no repeated number, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.

Example

Given [1,2,4], return 1.

算法:实现数学原理。比如对783921,每一位都对最后的index有一个加和的贡献,其中每一位加和的公式是:贡献 = 后面小的数的个数 * 后面共有多少个数!。具体比如对第一个‘7’这个数字,因为后面有‘1’,‘2’这【2】个数字比它小,字典序里曾经换到过它这个位置上,所以首先要想想当‘1’,‘2’在这个位置上时,它们后面的数字各产生过多少种排列,这个多少种答案就是【5!】,因为后面有5个不同的数字,随便排列的结果当然就是阶乘。

细节:阶乘的范围你一开始可以确定了的,所以做一个数组返回来会比较高效。另外注意模块化。

public class Solution {
    /*
     * @param A: An array of integers
     * @return: A long integer
     */
    public long permutationIndex(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return 0;
        }
        long result = 1;
        long[] factorial = findFactor(A);
        for (int i = 0; i < A.length; i++) {
            result += smallerCnt(A, i) * factorial[A.length - 1 - i];
        }
        return result;
        
    }
    
    private int smallerCnt(int[] A, int idx) {
        int cnt = 0;
        for (int i = idx + 1; i < A.length; i++) {
            if (A[i] < A[idx]) {
                cnt++;
            }
        }
        return cnt;
    }
    
    private long[] findFactor(int[] A) {
        long[] factorial = new long[A.length];
        if (A.length == 1) {
            return factorial;
        }
        factorial[1] = 1;
        for (int i = 2; i < factorial.length; i++) {
            factorial[i] = factorial[i - 1] * i;
        }
        return factorial;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7786655.html