华为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"
相关推荐
钉先生贾4 小时前
HarmonyOS 7.0性能与稳定性排障实战 05:真机预检、冷启动埋点与回归验证
华为·回归·harmonyos
默 语5 小时前
HarmonyOS7 表冠事件实战:onDigitalCrown、旋转调值与设备形态判断(附完整案例)
harmonyos
BK贝壳5 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
李小轰_Rex7 小时前
端侧AI实现:别急着上传,先看看这张图干不干净
harmonyos
搞IT的权哥7 小时前
从安卓转鸿蒙 AI 开发:哪些能力能直接搬,哪些要重写
鸿蒙·应用开发
HarmonyOS_SDK7 小时前
【HarmonyOS API 26】系统级熄屏导航,打造低功耗户外循迹新体验
harmonyos
码完就睡9 小时前
数据结构——图的基础概念
数据结构
Go-higher14 小时前
C语言--数据结构-栈、队列、堆
c语言·数据结构
郝学胜-神的一滴1 天前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机