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
Example 1:
Input:[1,2,4]
Output:1
Example 2:
Input:[3,2,1]
Output:6
思路:就是前面的数就是A[i] 右边有多少个比自己小的,乘以 (n-i)!,加起来就是前面的;最后再+1;
算法描述
只需计算有多少个排列在当前排列A
的前面即可。如何算呢?举个例子,[3,7,4,9,1]
,在它前面的必然是某位置i
对应元素比原数组小,而i
左侧和原数组一样。也即[3,7,4,1,X]
,[3,7,1,X,X]
,[3,1或4,X,X,X]
,[1,X,X,X,X]
。
而第i
个元素,比原数组小的情况有多少种,其实就是A[i]
右侧有多少元素比A[i]
小,乘上A[i]
右侧元素全排列数,即A[i]
右侧元素数量的阶乘。i
从右往左看