TikTok OA 面试真题解析:数组中的第 K 大元素

19次阅读
没有评论

Given an integer array nums and an integer k, return the k-th largest element in the array.

Note that it is the k-th largest element in the sorted order, not the k-th distinct element.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
function findKthLargest = (nums, k) {// ...}

这道题要求在整数数组中找出按降序排序后的第 k 大元素,注意这里统计的是“排序位置”,不是去重后的第 k 个不同值。常见做法是使用快速选择(Quickselect)在平均 O(n) 时间内定位目标元素,或者用大小为 k 的最小堆维护当前前 k 大元素。示例 1 中数组 [3,2,1,5,6,4] 的第 2 大是 5;示例 2 中数组 [3,2,3,1,2,4,5,5,6] 的第 4 大是 4。

正文完
 0