代码随想录day12| 239. 滑动窗口最大值、 347.前 K 个高频元素

题目链接: 239. 滑动窗口最大值

实现思路:用一个单调队列实现,单调队列出口是存放每个窗口的最大值,每结束一次窗口,就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; //返回原数组
}

 

题目链接:347.前 K 个高频元素  

代码实现

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;
}
 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值