Permutation Index I & II
2016-07-19 00:43
204 查看
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
Given [1,2,4], return 1.
分析:http://www.cnblogs.com/EdwardLiu/p/5104310.html
以4,1,2为例,4为第3大数,1为剩余序列第1大数,2为剩余序列第1大数,
故表达式为:2*2! + 0*1! + 0*0! + 1 = 5
以2,4,1为例,2为第2大数,4为剩余序列第2大数,1为剩余序列第1大数
故表达式为:1*2! + 1*1! + 0*0! + 1 = 4
这后面这个1一定要加,因为前面算的都是比该数小的数,加上这个1,才是该数是第几大数。
对于2*2!,2!表示当时当前位后面还有两位,全排列有2!种, 第一个2表示比4小的有两个数。全排列可以以它们开头。
Example
Given the permutation
分析:https://segmentfault.com/a/1190000004683277
与上一题的不同之处时会有重复的数。那么,只要在发现是重复数的那一位用
Example
Given [1,2,4], return 1.
分析:http://www.cnblogs.com/EdwardLiu/p/5104310.html
以4,1,2为例,4为第3大数,1为剩余序列第1大数,2为剩余序列第1大数,
故表达式为:2*2! + 0*1! + 0*0! + 1 = 5
以2,4,1为例,2为第2大数,4为剩余序列第2大数,1为剩余序列第1大数
故表达式为:1*2! + 1*1! + 0*0! + 1 = 4
这后面这个1一定要加,因为前面算的都是比该数小的数,加上这个1,才是该数是第几大数。
对于2*2!,2!表示当时当前位后面还有两位,全排列有2!种, 第一个2表示比4小的有两个数。全排列可以以它们开头。
public class Solution { public long permutationIndex(int[] A) { long index = 0, fact = 1; for (int i = A.length - 1; i >= 0; i--) { int numOfSmaller = 0; for (int j = i + 1; j < A.length; j++) { if (A[j] < A[i]) numOfSmaller++; // numOfSmaller refers to the numbers which can begin with; } index += numOfSmaller * fact; fact *= (A.length - i); } return index + 1; } }
Permutation Index II
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.Example
Given the permutation
[1, 4, 2, 2], return
3.
分析:https://segmentfault.com/a/1190000004683277
与上一题的不同之处时会有重复的数。那么,只要在发现是重复数的那一位用
numOfSmallers* fact的结果除以重复的次数
dup再加入index就可以了。当然,每个重复数的dup都要阶乘,例如有3个2,4个8,
dup就是
3! * 4! = 144。
index是所有previous排列的次数和,返回下一次
index+1。
import java.util.HashMap; public class Solution { 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 numOfSmallers = 0; for (int j = i + 1; j < A.length; j++) { if (A[j] < A[i]) numOfSmallers++; } index += numOfSmallers * fact / dup; fact *= (A.length - i); } return index + 1; } }
相关文章推荐
- 字符串与整形数之间的相互转化
- PCIE-SSD 随机读写性能对比测试(1)
- HDU 1532 Drainage Ditches(增广路dfs&bfs模板)
- Could not load file or assembly '$SharePoint.Project.AssemblyFullName$'
- maven学习(中)- 私服nexus搭建
- android 后台运行
- MySQL auto_increment实现
- NDK环境配置之Android Studio
- c语言字符串
- 联合索引优化多条件查询
- C++11:随机数库
- 发现几篇非常好的写集合的文章,不能转载,收藏会被挤吊,所以把地址写下来
- GreenPlum中自定义分区维护函数
- CTF牛刀小试
- 对日期进行模糊查询
- maven的使用
- KVC Collection Operators(集合操作)
- 《把时间当朋友》
- java多态总结以及动态绑定机制
- android 7.0带来的