unliar / unliar.github.io

一个已经不再使用的静态博客,新的博客在后边。
https://happysooner.com
0 stars 0 forks source link

实现查找 top k 大的数 #45

Open unliar opened 3 years ago

unliar commented 3 years ago
// 获取最大元素索引辅助函数
const GetMaxIndex = (nums) => {
  let targetIndex;
  nums.forEach((item, index) => {
    if (typeof targetIndex == "number") {
      // 获取最大的索引
      if (nums[targetIndex] <= item) {
        targetIndex = index;
      }
    } else {
      // 初始化
      targetIndex = index;
    }
  });
  return targetIndex;
};

const findKthLargest = (nums, k) => {
  let arr = [];
  while (arr.length < k) {
    const maxIndex = GetMaxIndex(nums);
    arr.push(nums[maxIndex]);
    delete nums[maxIndex];
  }
  return arr[k - 1];
};
unliar commented 3 years ago
  const findKthLargest = (nums, k) => {
    const ns =[...nums];
    let n =0; 
    while(n < k){
        n++;
        const maxIndex = GetMaxIndex(ns)
        if (n == k) {
            return ns[maxIndex];
        }
        ns.splice(maxIndex,1) // 删除
    }
  };