**[Lintcode]Permutation Index II排列序号II
2016-12-07 22:37
183 查看
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.每一位拥有一个系数k, 对于第i位,k=(len - i)!.例如第二位数字4的系数为(4-2)!=2!。此处代表的含义为:
假如我们固定前二位的数字(此时指针在第二位,则代表第一位固定仍为1。仅2,3,4位数字可以自由组合),那么可以出现的组合种类为2!×M
种。M代表第二位后,比第二位的数字小的数字出现的次数,此处为2,2,共两次。此处需要计算M,因为第二位不可以和第三四位一起全排列。因为为了保证在1,4,2,2的字典序之前,第二位也就是指针当前位必须小于4. 此时还需要除去重复元素的出现次数2!。所以指针在第二位时,排列种类为2!×2/2!个。 然后移动指针到下一位。
public class Solution {
/**
* @param A an integer array
* @return a long integer
*/
public long permutationIndexII(int[] A) {
long res = 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], map.get(A[i]) + 1);
dup *= map.get(A[i]);
} else {
map.put(A[i], 1);
}
int count = 0;
for(int j = i + 1; j < A.length; j++) {
if(A[j] < A[i]) count ++;
}
res += count * fact / dup;
fact *= (A.length - i);
}
return res + 1;
}
}
lexicographical order. The index begins at 1.
Example
Given the permutation
[1, 4, 2, 2], return
3.
分析:对于数组1,4,2,2.每一位拥有一个系数k, 对于第i位,k=(len - i)!.例如第二位数字4的系数为(4-2)!=2!。此处代表的含义为:
假如我们固定前二位的数字(此时指针在第二位,则代表第一位固定仍为1。仅2,3,4位数字可以自由组合),那么可以出现的组合种类为2!×M
种。M代表第二位后,比第二位的数字小的数字出现的次数,此处为2,2,共两次。此处需要计算M,因为第二位不可以和第三四位一起全排列。因为为了保证在1,4,2,2的字典序之前,第二位也就是指针当前位必须小于4. 此时还需要除去重复元素的出现次数2!。所以指针在第二位时,排列种类为2!×2/2!个。 然后移动指针到下一位。
public class Solution {
/**
* @param A an integer array
* @return a long integer
*/
public long permutationIndexII(int[] A) {
long res = 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], map.get(A[i]) + 1);
dup *= map.get(A[i]);
} else {
map.put(A[i], 1);
}
int count = 0;
for(int j = i + 1; j < A.length; j++) {
if(A[j] < A[i]) count ++;
}
res += count * fact / dup;
fact *= (A.length - i);
}
return res + 1;
}
}
相关文章推荐
- LintCode算法题解
- LintCode Majority Number iii
- LintCode-最大数
- lintCode Intersection of Two Arrays II
- Intersection of Two Arrays
- Subtree
- LintCode
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- lintcode之不同子序列数 + 序列II
- lintcode之快速幂
- lintcode删除排序数组中的重复数字 II
- lintcode之数组划分
- leetcode之三数之和 II
- lintcode之 数组剔除元素后的乘积
- lintcode之 合并排序数组 II
- lintcode 之子数组之和