华为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"
相关推荐
绝世番茄1 小时前
鸿蒙HarmonyOS ArkTS原生拖拽排序深度解析
深度学习·华为·list·harmonyos·鸿蒙
Georgewu3 小时前
【HarmonyOS AI 系列文章】 图像超分:用端侧 AI 实现小图传输,高清图呈现
harmonyos
不羁的木木4 小时前
HarmonyOS APP实战-画图APP - 第5篇:画笔属性调节
华为·harmonyos
玖玥拾5 小时前
C++ 数据结构 八大基础排序算法专题
数据结构·c++·算法·排序算法
想你依然心痛5 小时前
HarmonyOS 6(API 23)实战:基于HMAF的「智链中枢」——PC端AI智能体多Agent协同编排与任务调度平台
人工智能·华为·harmonyos·智能体
春卷同学5 小时前
HarmonyOS掌上记账APP开发实践第12篇:@Type 装饰器 — 解决嵌套对象响应式的终极方案
harmonyos
Tim_105 小时前
【C++】017、new/delete与malloc/free的区别
java·数据结构·算法
不羁的木木5 小时前
HarmonyOS APP实战-基于Image Kit的图像处理APP - 第9篇:批量处理与编辑历史
图像处理·ubuntu·harmonyos
春卷同学6 小时前
HarmonyOS掌上记账APP开发实践第15篇:ArkTS 类型系统深度解析 — 从接口到联合类型的灵活运用
ubuntu·华为·harmonyos
春卷同学6 小时前
HarmonyOS掌上记账APP开发实践第11篇:@Local 组件级状态 — 比 @State 更精确的局部状态管理
harmonyos