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

  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]。
而第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。
上面的1,2,3,4分别对应9,4,7,3,即每个元素右侧元素有多少个元素。

怎么理解这个阶乘呢?以i=1为例,此时A[1]=7,右侧有2个元素比它小,即4和1。把每个比它小的元素跟它对调,以4为例,有3,4,7,9,1。这里7,9,1可以混着排,共有3!种,这里3就是i=1右侧的元素。而1也可以跟7互换,故有2×3!。

代码如下:

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;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值