LintCode 197: Permutation Index (求第几个排列)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/90067205
  1. Permutation Index
    中文English
    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
Example 1:

Input:[1,2,4]
Output:1
Example 2:

Input:[3,2,1]
Output:6

解法1:
参考网上解法。举个例子[3,7,4,9,1]。从9开始往左看,统计每个元素右边有多少个元素比它小,假设在位置i的右边有k个元素比它小,则用k乘以i的阶乘即可。
而第i个元素,比原数组小的情况有多少种,其实就是A[i]右侧有多少元素比A[i]小,乘上A[i]右侧元素全排列数,即A[i]右侧元素数量的阶乘。i从右往左看,比当前A[i]小的右侧元素数量分别为1,1,2,1,所以最终字典序在当前A之前的数量为1×1!+1×2!+2×3!+1×4!=39,故当前A的字典序为40。

代码如下:

class Solution {
public:
    /**
     * @param A: An array of integers
     * @return: A long integer
     */
    long long permutationIndex(vector<int> &A) {
        int n = A.size();
        if (n <= 1) return n;
        long long result = 1;
        long long currFactorial = 1;
        for (int i = n - 2; i >= 0; --i) {
            int smallers = 0;
            for (int j = i + 1; j < n; ++j) {
                if (A[j] < A[i]) smallers++;
            }
            result += currFactorial * smallers;
            currFactorial *= n - i;
        }
        
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/90067205
今日推荐