-
Notifications
You must be signed in to change notification settings - Fork 639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
字节&leetcode215:数组中的第K个最大元素 #62
Comments
目前已经刷了两道Topk问题,不过于三种方案:
那么除了这两种方案还有没有其它的方式可解决本题喃?其实还有两种:
接下来一一解答😊 解法一:数组排序,取第 k 个数最简单 代码实现: let findKthLargest = function(nums, k) {
nums.sort((a, b) => b - a);
return nums[k-1]
}; 复杂度分析:
解法二:构造前
|
面向api开发👿
|
将数组前k项堆化,构造出小顶堆,堆顶元素与剩余数组中每个元素比较,大于堆顶元素则替换,然后堆化,这样可以保证堆中元素全部大于数组中的元素,则堆顶元素为第k个最大元素 var findKthLargest = function(nums, k) {
let heap = nums.slice(0, k);
buildHeap(heap);
let i = k;
while (i < nums.length) {
if (nums[i] > heap[0]) {
heap[0] = nums[i];
buildHeap(heap);
}
i++;
}
return heap[0];
};
function buildHeap(items) {
for (let i = ~~((items.length - 1) / 2);i >= 0;i--) {
heapify(items, i);
}
}
function swap(items, i, j) {
let temp = items[i];
items[i] = items[j];
items[j] = temp;
}
function heapify(items, i) {
let maxIndex = i;
while(true) {
let left = 2 * i + 1;
let right = left + 1;
if (left < items.length && items[left] < items[i]) {
maxIndex = left;
}
if (right < items.length && items[right] < items[maxIndex]) {
maxIndex = right;
}
if (maxIndex === i) break;
swap(items, i, maxIndex);
i = maxIndex;
}
} 时间复杂度:O(nlogk) |
这里的时间空间复杂度是 js 原生 sort 方法的复杂度么? |
是的,详见#59 (comment) |
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
示例 2:
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
附赠leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: