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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM