LeetCode刷题实战60:第k个排列
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 第k个排列,我们先来看题面:
https://leetcode-cn.com/problems/permutation-sequence/
The set [1,2,3,...,n] contains a total of n! unique permutations.
题意
样例
输入: n = 3, k = 3
输出: "213"
示例 2:
输入: n = 4, k = 9
输出: "2314"
解题
n = 3, k = 3
num = [1, 2, 3]
这三个数组成!"123"
"132"
"213"
"231"
"312"
"321"
1
,后面有组成两个数123
,132
,可以组成2个数.当首数字为2
,3
同样都是.k = 3
的数字 ,我们只需要 3/2
便可找到首数字什么,class Solution {
public String getPermutation(int n, int k) {
List<Integer> num = new ArrayList<>();
for (int i = 1; i <= n; i++) num.add(i);
int[] factorial = new int[n];
factorial[0] = 1;
for (int i = 1; i < n; i++) factorial[i] = i * factorial[i-1];
n--;
StringBuilder res = new StringBuilder();
while (n >= 0){
int t = factorial[n];
int loc = (int) (Math.ceil((double) k / (double) t)) - 1;
if (loc == -1) loc = num.size() - 1;
res.append(num.get(loc));
num.remove(loc);
k %= t;
n--;
}
return res.toString();
}
}
上期推文: