码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Permuation Index

时间:2015-10-05 14:15:28      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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.

class Solution {
public:
    /**
     * @param A an integer array
     * @return a long integer
     */
    long long permutationIndex(vector<int>& A) {
        long long len = A.size();
        if(len < 2) return len;
        
        vector<long long> factorial(len, 1);
        for(long long i = len - 2;i >= 0;--i)
            factorial[i] = factorial[i + 1] * (len - 1 - i);
        
        long long res = 1;
        for(long long i = 0;i < len;++i){
            long long num = 0;
            for(long long j = i + 1;j < len;++j)
                if(A[j] < A[i]) ++num;
            res += num * factorial[i];
        }
        return res;
    }
};

 

[LintCode] Permuation Index

标签:

原文地址:http://www.cnblogs.com/changchengxiao/p/4855643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!