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. Have you met this question in a real interview? Yes Example Given the permutation [1, 4, 2, 2], return 3.
這裏須要考慮重複元素,有無重複元素最大的區別在於原來的1!, 2!, 3!...
等須要除以重複元素個數的階乘。記錄重複元素個數一樣須要動態更新,引入哈希表這個萬能的工具較爲方便。工具
按照從數字低位到高位進行計算this
1 public class Solution { 2 /** 3 * @param A an integer array 4 * @return a long integer 5 */ 6 public long permutationIndexII(int[] A) { 7 // Write your code here 8 if (A==null || A.length==0) return new Long(0); 9 int len = A.length; 10 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 11 long index = 0, fact = 1, mulFact = 1; 12 for (int i=len-1; i>=0; i--) { 13 if (!map.containsKey(A[i])) { 14 map.put(A[i], 1); 15 } 16 else { 17 map.put(A[i], map.get(A[i])+1); 18 mulFact *= map.get(A[i]); 19 } 20 int count = 0; 21 for (int j=i+1; j<len; j++) { 22 if (A[i] > A[j]) count++; 23 } 24 index += count*fact/mulFact; 25 fact *= (len-i); 26 } 27 index = index + 1; 28 return index; 29 } 30 }