Lintcode: Permutation Index II

本文详细介绍了如何在存在重复元素的情况下,快速找到特定排列在所有排列中的序号。通过使用哈希表动态跟踪重复元素数量,并结合阶乘计算,实现高效的序号查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a permutation which may contain repeated numbers, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.

Have you met this question in a real interview? Yes
Example
Given the permutation [1, 4, 2, 2], return 3.

这里需要考虑重复元素,有无重复元素最大的区别在于原来的1!, 2!, 3!...等需要除以重复元素个数的阶乘。记录重复元素个数同样需要动态更新,引入哈希表这个万能的工具较为方便。

按照从数字低位到高位进行计算

 1 public class Solution {
 2     /**
 3      * @param A an integer array
 4      * @return a long integer
 5      */
 6     public long permutationIndexII(int[] A) {
 7         // Write your code here
 8         if (A==null || A.length==0) return new Long(0);
 9         int len = A.length;
10         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
11         long index = 0, fact = 1, mulFact = 1;
12         for (int i=len-1; i>=0; i--) {
13             if (!map.containsKey(A[i])) {
14                 map.put(A[i], 1);
15             }
16             else {
17                 map.put(A[i], map.get(A[i])+1);
18                 mulFact *= map.get(A[i]);
19             }
20             int count = 0;
21             for (int j=i+1; j<len; j++) {
22                 if (A[i] > A[j]) count++;
23             }
24             index += count*fact/mulFact;
25             fact *= (len-i);
26         }
27         index = index + 1;
28         return index;
29     }
30 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值