分析:搞一个哈希表,存储数组A中每一位A[i]的后面小于它的数的个数count。
为什么这样做呢,因为按照lexicographical order,小的数应该排在前面。那么A[i]后面小于A[i]的数有count个,而i前面又应该有n-i-1位,有(n-1-i)的阶乘种排列的可能,所以应该排在A[i]之前的可能排列就有count * (n-1-i)!个:所以遍历A[]中每一个数,计算在其之前的自然排列的数目,这些数目相加之和存入res,那么res的下一个数字就是现在数组A[]的排列。
比如:[2,1,4],hashmap中存放A[0],count=1;A[1],count=0;A[2],count=0; 然后第一位的阶乘为2!,第二位阶乘为1!,然后将前面的count与阶乘相乘之后累加。
如对于第一位2而言,1*2!表示第一位可以放得数只有1种可能,即1,然后1为第一位时的全排列有2!种,最后返回要++res返回,因为[1,2,4]即为第1个排列。
public class Solution { /** * @param A: An array of integers * @return: A long integer */ public long permutationIndex(int[] A) { // write your code here int len=A.length; long res=0; HashMap<Integer,Integer> hashMap=new HashMap<>(); for(int i=0;i<len;i++){ int count=0; for(int j=i+1;j<len;j++){ if(A[i]>A[j]){ count++; } } hashMap.put(A[i],count); } for(int i=0;i<len;i++){ //记录阶乘 long fact=1; for(int j=len-1-i;j>0;j--){ fact*=j; } res+=fact*hashMap.get(A[i]); } return ++res; } }