实现思路:用一个单调队列实现,单调队列出口是存放每个窗口的最大值,每结束一次窗口,就pop出出口元素,放入放回数组中,
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) {
int n = numsSize;
int queue[n]; //队列
int front = 0, rear = -1; //队首 队尾
int left = 0, right = 0; //窗口左下标 窗口右下标
while (right < n) { //窗口右移至终点
while (rear >= front && nums[right] > queue[rear]) rear--; //维护队列的单调性(非递增),即保证队首元素就是当前窗口的最大值
queue[++rear] = nums[right++]; //入队下一个窗口可能的最大值
if (left + k <= right) { //窗口大小大于k
if (nums[left] == queue[front]) front++; //如果最大值已经在窗口的左边,则将它永久出队
else nums[left] = queue[front]; //否则记录最大值进原数组中
left++; //左框右移
}
}
*returnSize = n - k + 1;
return nums; //返回原数组
}
代码实现
struct hash_table {
int key;
int val;
UT_hash_handle hh;
};typedef struct hash_table* hash_ptr;
struct pair {
int first;
int second;
};struct pair* heap;
int heapSize;void swap(struct pair* a, struct pair* b) {
struct pair t = *a;
*a = *b, *b = t;
}bool cmp(struct pair* a, struct pair* b) {
return a->second < b->second;
}struct pair top() {
return heap[1];
}int push(hash_ptr x) {
heap[++heapSize].first = x->key;
heap[heapSize].second = x->val;
int p = heapSize, s;
while (p > 1) {
s = p >> 1;
if (cmp(&heap[s], &heap[p])) return;
swap(&heap[p], &heap[s]);
p = s;
}
}int pop() {
heap[1] = heap[heapSize--];
int p = 1, s;
while ((p << 1) <= heapSize) {
s = p << 1;
if (s < heapSize && cmp(&heap[s + 1], &heap[s])) s++;
if (cmp(&heap[p], &heap[s])) return;
swap(&heap[p], &heap[s]);
p = s;
}
}int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
hash_ptr head = NULL;
hash_ptr p = NULL, tmp = NULL;for (int i = 0; i < numsSize; i++) {
HASH_FIND_INT(head, &nums[i], p);
if (p == NULL) {
p = malloc(sizeof(struct hash_table));
p->key = nums[i];
p->val = 1;
HASH_ADD_INT(head, key, p);
} else {
p->val++;
}
}heap = malloc(sizeof(struct pair) * (k + 1));
heapSize = 0;HASH_ITER(hh, head, p, tmp) {
if (heapSize == k) {
struct pair tmp = top();
if (tmp.second < p->val) {
pop();
push(p);
}
} else {
push(p);
}
}
*returnSize = k;
int* ret = malloc(sizeof(int) * k);
for (int i = 0; i < k; i++) {
struct pair tmp = top();
pop();
ret[i] = tmp.first;
}
return ret;
}