题目
设计一个找到数据流中第 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); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
提示:
1 <= k <= 104
0 <= nums.length <= 104
-104 <= nums[i] <= 104
-104 <= val <= 104
最多调用 add 方法 104 次
题目数据保证,在查找第 k 大元素时,数组中至少有 k 个元素
来源:力扣(LeetCode)
解题
模板:
typedef struct {
} KthLargest;
KthLargest* kthLargestCreate(int k, int* nums, int numsSize) {
}
int kthLargestAdd(KthLargest* obj, int val) {
}
void kthLargestFree(KthLargest* obj) {
}
/**
* Your KthLargest struct will be instantiated and called as such:
* KthLargest* obj = kthLargestCreate(k, nums, numsSize);
* int param_1 = kthLargestAdd(obj, val);
* kthLargestFree(obj);
*/
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);
}