198. 排列序号II
给出一个可能包含重复数字的排列,求这些数字的所有排列按字典序排序后该排列在其中的编号。编号从1开始。
样例
样例 1:
输入:[1,4,2,2]
输出:3
样例 2:
输入 :[1,6,5,3,1]
输出:24
public class Solution {
/**
* @param A: An array of integers
* @return: A long integer
*/
public long permutationIndexII(int[] A) {
long result = 0, permutation = 1, repeat = 1;
Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
int len = A.length;
for (int i = len - 1; i >= 0; i--) {
if (counter.containsKey(A[i])) {
counter.put(A[i], counter.get(A[i]) + 1);
repeat *= counter.get(A[i]);
} else {
counter.put(A[i], 1);
}
int smaller = 0;
for (int j = i + 1; j < len; j++) {
if (A[j] < A[i]) {
smaller++;
}
}
result += smaller * permutation / repeat;
permutation *= len - i;
}
return result + 1;
}
}