**[Lintcode]Permutation Index II排列序号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.

分析:对于数组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;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值