码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode - Permutation index

时间:2015-11-25 10:11:23      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Thought:

1)Initial thought:

 - sort all numbers in ascending order;

 - index+=index in sorted list * factor;

 - factor /=(A.length-i);

Time complexity: sort- (nlogn) + loop(N * N-remove element from list) ===> o(N^2)

Space complexity: O(N)

  public long permutationIndex(int[] A) {
        // Write your code here
        if(A==null||A.length==0){
            return 0;
        }
        List<Integer> li=new ArrayList<Integer>();
        for(int i=0;i<A.length;i++){
            li.add(A[i]);
        }
        Collections.sort(li);
        long res=1;
        long factor=1;
        for(int i=2;i<A.length;i++){
            factor*=i;
        }
        int i=0;
        while(li.size()>1){
            int cur=li.indexOf(A[i++]);
            res+=cur*factor;
            li.remove(cur);
            factor/=(A.length-i);
        }
        return res;
    }

2) Optimized Solution

Original source: http://algorithm.yuanbin.me/zh-cn/exhaustive_search/previous_permuation.html

 - for each element at index i from outer loop,we check elements right after it. If current element > any following element,rank++;

 - index+= rank(number of elements smaller than this number)*factor(number of combinations for each number);

 - factor*=length-i; 

Time complexity:O(N^2); 

Space complexity:O(1);

    public long permutationIndex(int[] A) {
        // Write your code here
        if(A==null||A.length==0){
            return 0;
        }
        long res=1;
        long factor=1;
        for(int i=A.length-1;i>=0;i--){
            int count=0;
            for(int j=i+1;j<A.length;j++){
                if(A[i]>A[j]){
                    count++;
                }
            }
            res+=count*factor;
            factor*=(A.length-i);
        }
        return res;
    }

 

 

 

 

Lintcode - Permutation index

标签:

原文地址:http://www.cnblogs.com/fifi043/p/4993657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!