Lintcode: Permutation Index

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.

 

在计算最终的 index 时需要动态计算某个数的相对大小。我们可通过两重循环得出到某个索引处值的相对大小。

 

正确

以4,1,2为例,4为第3大数,1为剩余序列第1大数,2为剩余序列第1大数,

故表达式为:(3-1)*2! + (1-1)*1! + (1-1)*0! + 1 = 5

以2,4,1为例,2为第2大数,4为剩余序列第2大数,1为剩余序列第1大数

故表达式为:(2-1)*2! + (2-1)*1! + (1-1)*0! + 1 = 4

这后面这个1一定要加,因为前面算的都是比该数小的数,加上这个1,才是该数是第几大数。

2!表示当时当前位后面还有两位,全排列有2!种

 1 public class Solution {
 2     /**
 3      * @param A an integer array
 4      * @return a long integer
 5      */
 6     public long permutationIndex(int[] A) {
 7         // Write your code here
 8         long res = 0;
 9         int n = A.length;
10         long fact = 1;
11         for (int i=1; i<n; i++) {
12             fact *= i; //fact should at last equal (n-1)!
13         }
14         int initial = n-1; //use to update factorial
15         for (int i=0; i<n; i++) {
16             long count = 0;
17             for (int j=i; j<n; j++) {
18                 if (A[i] >= A[j]) {
19                     count++;
20                 }
21             }
22             res += (count-1)*fact;
23             if (initial != 0) {
24                 fact /= initial;
25                 initial--;
26             }
27         }
28         res = res + 1;
29         return res;
30     }
31 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/5104310.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值