题目链接:
数据流中的第 K 大元素
有关题目
设计一个找到数据流中第 k 大元素的类(class)。
注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。
示例:
输入:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
输出:
[null, 4, 5, 5, 8, 8]
解释:
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);
kthLargest.add(5);
kthLargest.add(10);
kthLargest.add(9);
kthLargest.add(4);
提示:
1 <= k <= 10^4
0 <= nums.length <= 10^4
-104 <= nums[i] <= 10^4
-10^4 <= val <= 10^4
最多调用 add 方法 10^4 次
题目数据保证,在查找第 k 大元素时,数组中至少有 k 个元素
题解
法一:优先队列 参考动画理解Hao Kun Yang 参考负雪明烛 参考TopK理解 参考快排算法
struct Heap {
int* heap;
int heapSize;
bool (*cmp)(int, int);
};
void init(struct Heap* obj, int n, bool (*cmp)(int, int)) {
obj->heap = malloc(sizeof(int) * (n + 1));
obj->heapSize = 0;
obj->cmp = cmp;
}
bool cmp(int a, int b){
return a > b;
}
void swap(int* a, int* b){
int tmp = *a;
*a = *b, *b = tmp;
}
void push(struct Heap* obj, int x){
int p = ++(obj->heapSize), q = p >> 1;
obj->heap[p] = x;
while (q){
if (!obj->cmp(obj->heap[q], obj->heap[p])) {
break;
}
swap(&(obj->heap[q]), &(obj->heap[p]));
p = q, q = p >> 1;
}
}
void pop(struct Heap* obj) {
swap(&(obj->heap[1]), &(obj->heap[(obj->heapSize)--]));
int p = 1, q = p << 1;
while (q <= obj->heapSize) {
if (q + 1 <= obj->heapSize) {
if (obj->cmp(obj->heap[q], obj->heap[q + 1])) {
q++;
}
}
if (!obj->cmp(obj->heap[p], obj->heap[q])) {
break;
}
swap(&(obj->heap[q]), &(obj->heap[p]));
p = q, q = p << 1;
}
}
int top(struct Heap* obj) {
return obj->heap[1];
}
typedef struct {
struct Heap* heap;
int maxSize;
} KthLargest;
KthLargest* kthLargestCreate(int k, int* nums, int numsSize) {
KthLargest* ret = malloc(sizeof(KthLargest));
ret->heap = malloc(sizeof(struct Heap));
init(ret->heap, k + 1, cmp);
ret->maxSize = k;
for (int i = 0; i < numsSize; i++) {
kthLargestAdd(ret, nums[i]);
}
return ret;
}
int kthLargestAdd(KthLargest* obj, int val) {
push(obj->heap, val);
if (obj->heap->heapSize > obj->maxSize) {
pop(obj->heap);
}
return top(obj->heap);
}
void kthLargestFree(KthLargest* obj) {
free(obj->heap->heap);
free(obj->heap);
free(obj);
}
|