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.
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 = , fact = ;
for (int i = A.length - ; i >= ; i--) {
int numOfSmaller = ;
for (int j = i + ; 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 + ;
}
}
Permutation Index II
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 = , fact = , dup = ;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = A.length - ; i >= ; i--) {
if (!map.containsKey(A[i])) {
map.put(A[i], );
} else {
map.put(A[i], map.get(A[i]) + );
dup *= map.get(A[i]);
}
int numOfSmallers = ;
for (int j = i + ; j < A.length; j++) {
if (A[j] < A[i])
numOfSmallers++;
}
index += numOfSmallers * fact / dup;
fact *= (A.length - i);
}
return index + ;
}
}