Lintcode: Permutation Index
Given a permutation which contains no repeated number, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.
在计算最终的 index 时需要动态计算某个数的相对大小。我们可通过两重循环得出到某个索引处值的相对大小。
正确
以4,1,2为例,4为第3大数,1为剩余序列第1大数,2为剩余序列第1大数,
故表达式为:(3-1)*2! + (1-1)*1! + (1-1)*0! + 1 = 5
以2,4,1为例,2为第2大数,4为剩余序列第2大数,1为剩余序列第1大数
故表达式为:(2-1)*2! + (2-1)*1! + (1-1)*0! + 1 = 4
这后面这个1一定要加,因为前面算的都是比该数小的数,加上这个1,才是该数是第几大数。
2!表示当时当前位后面还有两位,全排列有2!种
1 public class Solution { 2 /** 3 * @param A an integer array 4 * @return a long integer 5 */ 6 public long permutationIndex(int[] A) { 7 // Write your code here 8 long res = 0; 9 int n = A.length; 10 long fact = 1; 11 for (int i=1; i<n; i++) { 12 fact *= i; //fact should at last equal (n-1)! 13 } 14 int initial = n-1; //use to update factorial 15 for (int i=0; i<n; i++) { 16 long count = 0; 17 for (int j=i; j<n; j++) { 18 if (A[i] >= A[j]) { 19 count++; 20 } 21 } 22 res += (count-1)*fact; 23 if (initial != 0) { 24 fact /= initial; 25 initial--; 26 } 27 } 28 res = res + 1; 29 return res; 30 } 31 }