您的位置:首页 > 其它

**[Lintcode]Permutation Index II排列序号II

2016-12-07 22:37 183 查看
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,4,2,2.每一位拥有一个系数k, 对于第i位,k=(len - i)!.例如第二位数字4的系数为(4-2)!=2!。此处代表的含义为:

假如我们固定前二位的数字(此时指针在第二位,则代表第一位固定仍为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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode