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 時須要動態計算某個數的相對大小。咱們可經過兩重循環得出到某個索引處值的相對大小。spa
正確code
以4,1,2爲例,4爲第3大數,1爲剩餘序列第1大數,2爲剩餘序列第1大數,blog
故表達式爲:(3-1)*2! + (1-1)*1! + (1-1)*0! + 1 = 5索引
以2,4,1爲例,2爲第2大數,4爲剩餘序列第2大數,1爲剩餘序列第1大數it
故表達式爲:(2-1)*2! + (2-1)*1! + (1-1)*0! + 1 = 4io
這後面這個1必定要加,由於前面算的都是比該數小的數,加上這個1,纔是該數是第幾大數。ast
2!表示當時當前位後面還有兩位,全排列有2!種class
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 }