Skip to content

Commit 71c1ae4

Browse files
committed
add permutation index
1 parent 67d083c commit 71c1ae4

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@
113113
* [Next Permutation](exhaustive_search/next_permutation.md)
114114
* [Previous Permuation](exhaustive_search/previous_permuation.md)
115115
* [Unique Binary Search Trees II](exhaustive_search/unique_binary_search_trees_ii.md)
116+
* [Permutation Index](exhaustive_search/permutation_index.md)
116117
* [Dynamic Programming - 动态规划](dynamic_programming/README.md)
117118
* [Triangle](dynamic_programming/triangle.md)
118119
* [Knapsack - 背包问题](dynamic_programming/knapsack.md)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Permutation Index
2+
3+
## Source
4+
5+
- lintcode: [(197) Permutation Index](http://www.lintcode.com/en/problem/permutation-index/)
6+
7+
```
8+
Given a permutation which contains no repeated number,
9+
find its index in all the permutations of these numbers,
10+
which are ordered in lexicographical order. The index begins at 1.
11+
12+
Example
13+
Given [1,2,4], return 1.
14+
```
15+
16+
## 题解1 - 双重 for 循环
17+
18+
### Java
19+
20+
```java
21+
public class Solution {
22+
/**
23+
* @param A an integer array
24+
* @return a long integer
25+
*/
26+
public long permutationIndex(int[] A) {
27+
if (A == null || A.length == 0) return 0;
28+
29+
long index = 1;
30+
long factor = 1;
31+
for (int i = A.length - 1; i >= 0; i--) {
32+
int rank = 0;
33+
for (int j = i + 1; j < A.length; j++) {
34+
if (A[i] > A[j]) rank++;
35+
}
36+
index += rank * factor;
37+
factor *= (A.length - i);
38+
}
39+
40+
return index;
41+
}
42+
}
43+
```
44+
45+
## 题解2 - 哈希表
46+
47+
## Reference
48+
49+
- [Permutation Index](http://www.geekviewpoint.com/java/numbers/permutation_index)
50+
- [permutation-index | 九章算法](http://www.jiuzhang.com/solutions/permutation-index/)

0 commit comments

Comments
 (0)