198.Permutation Index II-排列序号II(中等题)
来源:互联网 发布:破特大网络贩枪案 编辑:程序博客网 时间:2024/06/06 00:41
排列序号II
题目
给出一个可能包含重复数字的排列,求这些数字的所有排列按字典序排序后该排列在其中的编号。编号从1开始。
样例
给出排列[1, 4, 2, 2],其编号为3。
题解
对于无重复元素的数组,首先在哈希表中存储数组中每一位A[i]的后面小于它的数的个数count,而i前面又应该有n-i-1位,就有(n-1-i)!种排列的可能,所以在A[i]之前的可能排列就有count * (n-1-i)!个。所以遍历数组,所有元素的count * (n-1-i)!之和再加1就是当前排列的序号。
而本题数组是有重复元素的,所以需要排除重复排列。如果A[i]在[0,i]区间中有重复元素,则用A[i]的count * fact的结果除以重复次数dup的阶乘。
public class Solution { /** * @param A an integer array * @return a long integer */ public long permutationIndexII(int[] A) { long index = 0, fact = 1, dup = 1; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = A.length-1; i >= 0; i--) { if (!map.containsKey(A[i])) { map.put(A[i], 1); } else { map.put(A[i], map.get(A[i])+1); dup *= map.get(A[i]); } int count = 0; for (int j = i+1; j < A.length; j++) { if (A[j] < A[i]) { count++; } } index += count * fact / dup; fact *= (A.length - i); } return index+1; }}
Last Update 2016.11.2
0 0
- 198.Permutation Index II-排列序号II(中等题)
- **[Lintcode]Permutation Index II排列序号II
- 190.Next Permutation II-下一个排列(中等题)
- 197.Permutation Index-排列序号(容易题)
- lintcode Permutation Index 排列序号
- 排列序号II
- 排列序号II-LintCode
- 排列序号II
- LintCode_198 Permutation Index II
- #198 Permutation Index II
- [LintCode] Permutation Index I & Permutation Index II
- Lintcode(198) Permutation Index II
- 16.Permutations II-带重复元素的排列(中等题)
- 51.Previous Permutation-上一个排列(中等题)
- 52.Next Permutation-下一个排列(中等题)
- 388.Permutation Sequence-第k个排列(中等题)
- 4.Ugly Number II-丑数 II(中等题)
- 47.Majority number II-主元素 II(中等题)
- play的模板语法
- 一个完整的Servlet需要哪些。
- TabLayout禁止选择
- OpenGL ES 纹理设置
- HTML5 表单元素在 Android 下被软键盘遮挡
- 198.Permutation Index II-排列序号II(中等题)
- 225. Implement Stack using Queues
- iOS 开发中你是否遇到这些经验问题
- 号码归属地的Jar包
- epoll的总结 LT和ET使用EPOLLONESHOT
- Jquery datatables 列过多,固定前两列保持不动
- MyBatis学习总结(四)——解决字段名与实体类属性名不相同的冲突
- JavaScript的三种弹窗消息框:alert+prompt+confirm 结合代码
- 161031