排列序号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