快速排序找出第K大的元素

有序数组里第 K 大的元素就是index 为 array.length - k 的元素。
快速排序的思路主要就是选一个基准值p,然后将小于p的值放在p的左右,大于p的值放在p的右边,然后对左右数组进行递归。
利用这个思路,当我们找到这个基准值对应的 index,等于我们要找的index时,就可以了,不用管左右两边是否是有序的。

先看未优化版。这里是新建数组分别用来存比基准值小和大的元素

function findKthLargest(input, k) {
  const len = input.length;
  if (len < 2) return input;
  let nums = input.concat([]);

  const getQuickSortIndex = (startIndex, endIndex) => {
    const len = endIndex - startIndex + 1;
    const pivotIndex = (len >>> 1) + startIndex;
    const pivotValue = nums[pivotIndex];
    const leftArr = [];
    const rightArr = [];
    for (let i = startIndex; i <= endIndex; i++) {
      if (i === pivotIndex) continue; //不把基准值独立出来,会造成无限递归
      if (nums[i] <= pivotValue) {
        leftArr.push(nums[i]);
      } else {
        rightArr.push(nums[i]);
      }
    }
    nums.splice(startIndex,len,...[...leftArr, pivotValue, ...rightArr]) ;
    return startIndex + leftArr.length;
  };

  let targetIndex = nums.length - k;
  let start = 0,
    end = nums.length - 1;
  let index = getQuickSortIndex(start, end);
  while (index != targetIndex) {
    if (index > targetIndex) {
      end = index - 1;
    } else {
      start = index + 1;
    }
    index = getQuickSortIndex(start, end);
  }
  return nums[index];
}

然后看优化版,不新建数组,直接在原数组上操作
在这里插入图片描述

function getQuickSortIndex(arr, startIndex, endIndex) {
  let pivot = arr[startIndex];
  let prev = startIndex;
  for (let i = startIndex + 1; i <= endIndex; i++) {
    if (arr[i] < pivot) {
      prev++;
      [arr[prev], arr[i]] = [arr[i], arr[prev]];
    }
  }
  arr[startIndex] = arr[prev];
  arr[prev] = pivot;
  return prev;
}

function findKthLargest_1(nums, k) {
  const len = nums.length;
  if (len < 2) return nums;

  let targetIndex = nums.length - k;
  let start = 0,
    end = nums.length - 1;
  let index = getQuickSortIndex(nums, start, end);
  while (index != targetIndex) {
    if (index > targetIndex) {
      end = index - 1;
    } else {
      start = index + 1;
    }
    index = getQuickSortIndex(nums, start, end);
  }
  return nums[index];
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值