leetcode 911. 在线选举

在线选举问题解决与优化
该博客详细介绍了如何解决LeetCode上的在线选举问题。通过预处理和使用upper_bound函数,实现了在O(n log n)的时间复杂度内查询每个时刻的票数最多的人。每个测试用例最多调用10^4次查询,查询复杂度为O(x log n)。博客内容涵盖了数据结构、算法和高效查询策略。

题目传送门

链接:https://leetcode-cn.com/problems/online-election/

题干

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

题解

每个测试用例会最多调用 10410^4104 次查询,每次查询时刻 ttt 时票数最多的人

可以知道,如果 t 时刻没有投票,那么时刻 t 的答案就是前一次投票时的答案

如果时刻 t 投票了,那么答案就是此次投票的答案

使用 upper_bound 函数查询大于 t 的时间序号 idx,times[idx-1] 时刻票数最多的人就是答案

预处理 res 和 times 数组的时间复杂度为 O(n),设查询次数为 x,查询复杂度为 O(xlogn)

Code

class TopVotedCandidate {
public:
    int res[5005], n;
    int times[5005];
    TopVotedCandidate(vector<int>& persons, vector<int>& times) {
        // 数组长度
        n = times.size();
        // cnts 记录每个候选人的票数
        map<int, int> cnts;
        // cur 是当前最高票数的人
        int cur = -1;
        for (int i = 0; i < n; i++) {
            this -> times[i] = times[i];
            cnts[persons[i]]++;
            if (cur == - 1 || cnts[persons[i]] >= cnts[cur]) {
                cur = persons[i];
            }
            // 记录当前时刻票数最多的人
            res[i] = cur;
        }
    }
    
    int q(int t) {
        int idx = upper_bound(times, times + n, t) - times - 1;
        return res[idx];
    }
};

/**
 * Your TopVotedCandidate object will be instantiated and called as such:
 * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);
 * int param_1 = obj->q(t);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值