public class Solution {
/**
* @param A an integer array
* @return a long integer
*/
public long permutationIndexII(int[] A) {
// Write your code here
long index=0;
for(int i=0;i<A.length;i++){
int count=0;
for(int j=i+1;j<A.length;j++){
if(A[j]<A[i]){
count++;
}
}
if(count>0){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int j=i;j<A.length;j++){
if(!map.containsKey(A[j])){
map.put(A[j], 1);
}else{
int temp=map.get(A[j]);
map.put(A[j], ++temp);
}
}
int size=0;
Set<Integer> set=map.keySet();
List<Integer> list=new ArrayList<Integer>();
for(Integer e:set){
list.add(map.get(e));
if(e<A[i]){
size+=map.get(e);
}
}
long fenZi=size*factorial(A.length-i-1);
long fenMu=1;
for(int j=0;j<list.size();j++){
fenMu*=factorial(list.get(j));
}
index+=fenZi/fenMu;
}
}
return index+1;
}
private static long factorial(int n){
if(n==1){
return 1;
}else{
return factorial(n-1)*n;
}
}
}
Java实现-排列序号2
最新推荐文章于 2024-05-26 22:32:25 发布