• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2016-01-06 07:56  neverlandly  阅读(2052)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3