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
.
假如我们固定前二位的数字(此时指针在第二位,则代表第一位固定仍为1。仅2,3,4位数字可以自由组合),那么可以出现的组合种类为2!×M 种。M代表第二位后,比第二位的数字小的数字出现的次数,此处为2,2,共两次。此处需要计算M,因为第二位不可以和第三四位一起全排列。因为为了保证在1,4,2,2的字典序之前,第二位也就是指针当前位必须小于4. 此时还需要除去重复元素的出现次数2!。所以指针在第二位时,排列种类为2!×2/2!个。 然后移动指针到下一位。
public class Solution {
/**
* @param A an integer array
* @return a long integer
*/
public long permutationIndexII(int[] A) {
long res = 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], map.get(A[i]) + 1);
dup *= map.get(A[i]);
} else {
map.put(A[i], 1);
}
int count = 0;
for(int j = i + 1; j < A.length; j++) {
if(A[j] < A[i]) count ++;
}
res += count * fact / dup;
fact *= (A.length - i);
}
return res + 1;
}
}