给出一个不含重复数字的排列,求这些数字的所有排列按字典序排序后该排列的编号。其中,编号从1开始。
例如,排列[1,2,4]是第1个排列,第二个[1,4,2],第六个为[4,2,1]
public
class Solution {
/**
* @param A an integer array
* @return a long integer
* 对4个数的排列,各位的权值为:3!,2!,1!,0!。
* 第一位之后的数小于第一位的个数是x,第二位之后的数小于第二位的个数是y
* ,第三位之后的数小于第三的个数是z,第四位之后的数小于第四位的个数是w
* ,则abcd排列所在的序列号:index = x*3!+y*2!+z*1!,<0!=0> 编号从0开始
*/
public long permutationIndex(int[] A) {
// Write your code here
long index = 0;//记录序号
long position = 2;//数字的位置
long weight = 1;//权值
//从倒数第二位开始数,看他的后面有几个小于他的数
for (int i = A.length - 2; i >= 0; i--){
long count = 0;
for (int j = i + 1; j < A.length; j++){
if (A[j] < A[i]){
count++;
}
}
index += (weight * count);
weight *= position;
position += 1;
}
return (index + 1);
}
}