Lintcode - Permutation index

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;
    }

 

 

 

 

posted @ 2015-11-25 09:19  fifi努刷题  阅读(167)  评论(0)    收藏  举报