* 197. Permutation Index【LintCode by java】

Description

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.

Example

Given [1,2,4], return 1.

解题:至今仍然不理解这个“字典中的顺序”是什么意思,做个标记日后有时间再看。照着人家的代码敲得:https://www.cnblogs.com/theskulls/p/4881142.html      代码如下:

 1 public class Solution {
 2     /**
 3      * @param A: An array of integers
 4      * @return: A long integer
 5      */
 6     public long permutationIndex(int[] A) {
 7         // write your code here
 8         long index = 0;
 9         long position = 2;
10         long factor = 1;
11         for (int p = A.length - 2; p >= 0; p--) {
12             long successors = 0;
13             for (int q = p + 1; q < A.length; q++) {
14                 if (A[p] > A[q]) {
15                     successors++;
16                 }
17             }
18         index += (successors * factor);
19         factor *= position;
20         position++;
21         }
22         index = index + 1;
23         return index;
24         }
25 }

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9202492.html