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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值