华为OD机考题加答案之输出指定位置的数字

【第k个排列】给定参数n,从1到n会有n个整数:1,2,3,...n,这n个数字共有n!种排列。按大小顺序升序列出所有排列情况,并一一标记,当n=3时,所有排列如下:

"123"

"132"

"213"

"231"

"312"

"321"

给定n和k,返回第k个排列。

输入描述:

输入两行,

第一行为n,

第二行为k,给定n的范围是1,9,给定k的范围是1,n!

输出描述:

输出排在第k位置的数字:

示例1:

输入:

3

3

输出:

213

复制代码
function factorial(num: number): number {
  let result = 1;
  for (let i = 2; i <= num; i++) {
    result *= i;
  }
  return result;
}

function findKthPermutation(nums: number[], k: number): string {
  if (nums.length === 1) {
    return nums[0].toString();
  }

  const n = nums.length;
  const fact = factorial(n - 1);
  const index = Math.floor((k - 1) / fact);
  const chosen = nums[index];
  nums.splice(index, 1);

  return chosen.toString() + findKthPermutation(nums, k - index * fact);
}

function getPermutation(n: number, k: number): string {
  const nums: number[] = [];
  for (let i = 1; i <= n; i++) {
    nums.push(i);
  }

  return findKthPermutation(nums, k);
}

// 测试示例
console.log(getPermutation(3, 3)); // 输出: "213"
console.log(getPermutation(4, 9)); // 输出: "2314"
console.log(getPermutation(3, 1)); // 输出: "123"
相关推荐
Darling噜啦啦13 小时前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
Junerver19 小时前
把 DevEco Code 的 HarmonyOS 开发能力装进口袋——harmonyos-dev-skill
harmonyos
程序猿追1 天前
那个右下角的小数字怎么“卡”住我打字——我用 HarmonyOS 自己写了一个字数限制输入框
pytorch·华为·harmonyos
古德new1 天前
鸿蒙PC使用electron迁移:Joplin Electron 桌面适配全记录
华为·electron·harmonyos
世人万千丶2 天前
桌面便签小应用 - HarmonyOS ArkUI 开发实战-TextArea与Flex布局-PC版本
华为·harmonyos·鸿蒙·鸿蒙系统
慧海灵舟2 天前
AGenUI 鸿蒙端实战踩坑录:从 Column 布局消失到异步组件宽度为 0
华为·harmonyos
yuegu7772 天前
HarmonyOS应用<节气通>开发第33篇:状态管理实战
华为·harmonyos
小小工匠2 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
YM52e2 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统