您的位置:首页 > 其它

Permutation Index I & II

2016-07-19 00:43 204 查看
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.

分析:http://www.cnblogs.com/EdwardLiu/p/5104310.html

以4,1,2为例,4为第3大数,1为剩余序列第1大数,2为剩余序列第1大数,

故表达式为:2*2! + 0*1! + 0*0! + 1 = 5

以2,4,1为例,2为第2大数,4为剩余序列第2大数,1为剩余序列第1大数

故表达式为:1*2! + 1*1! + 0*0! + 1 = 4

这后面这个1一定要加,因为前面算的都是比该数小的数,加上这个1,才是该数是第几大数。

对于2*2!,2!表示当时当前位后面还有两位,全排列有2!种, 第一个2表示比4小的有两个数。全排列可以以它们开头。

public class Solution {
public long permutationIndex(int[] A) {
long index = 0, fact = 1;
for (int i = A.length - 1; i >= 0; i--) {
int numOfSmaller = 0;
for (int j = i + 1; j < A.length; j++) {
if (A[j] < A[i]) numOfSmaller++;  // numOfSmaller refers to the numbers which can begin with;
}
index += numOfSmaller * fact;
fact *= (A.length - i);
}
return index + 1;
}
}


Permutation Index II

Given a permutation which may contain repeated numbers, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.
Example

Given the permutation
[1, 4, 2, 2]
, return
3
.

分析:https://segmentfault.com/a/1190000004683277

与上一题的不同之处时会有重复的数。那么,只要在发现是重复数的那一位用
numOfSmallers* fact
的结果除以重复的次数
dup
再加入index就可以了。当然,每个重复数的dup都要阶乘,例如有3个2,4个8,
dup
就是
3! * 4! = 144
index
是所有previous排列的次数和,返回下一次
index+1


import java.util.HashMap;

public class Solution {
public long permutationIndexII(int[] A) {
long index = 0, fact = 1, dup = 1;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = A.length - 1; i >= 0; i--) {
if (!map.containsKey(A[i])) {
map.put(A[i], 1);
} else {
map.put(A[i], map.get(A[i]) + 1);
dup *= map.get(A[i]);
}
int numOfSmallers = 0;
for (int j = i + 1; j < A.length; j++) {
if (A[j] < A[i])
numOfSmallers++;
}
index += numOfSmallers * fact / dup;
fact *= (A.length - i);
}
return index + 1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: