【解题报告】Leecode911. 在线选举——Leecode每日一题系列
題目鏈接:https://leetcode-cn.com/problems/online-election/
題解匯總:https://zhanglong.blog.csdn.net/article/details/121071779
題目描述
給你兩個整數數組 persons 和 times 。在選舉中,第 i 張票是在時刻為 times[i] 時投給候選人 persons[i] 的。
對于發生在時刻 t 的每個查詢,需要找出在 t 時刻在選舉中領先的候選人的編號。
在 t 時刻投出的選票也將被計入我們的查詢之中。在平局的情況下,最近獲得投票的候選人將會獲勝。
實現 TopVotedCandidate 類:
TopVotedCandidate(int[] persons, int[] times) 使用 persons 和 times 數組初始化對象。
int q(int t) 根據前面描述的規則,返回在時刻 t 在選舉中領先的候選人的編號。
示例:
輸入:
[“TopVotedCandidate”, “q”, “q”, “q”, “q”, “q”, “q”]
[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]
輸出:
[null, 0, 1, 1, 0, 0, 1]
解釋:
TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);
topVotedCandidate.q(3); // 返回 0 ,在時刻 3 ,票數分布為 [0] ,編號為 0 的候選人領先。
topVotedCandidate.q(12); // 返回 1 ,在時刻 12 ,票數分布為 [0,1,1] ,編號為 1 的候選人領先。
topVotedCandidate.q(25); // 返回 1 ,在時刻 25 ,票數分布為 [0,1,1,0,0,1] ,編號為 1 的候選人領先。(在平局的情況下,1 是最近獲得投票的候選人)。
topVotedCandidate.q(15); // 返回 0
topVotedCandidate.q(24); // 返回 0
topVotedCandidate.q(8); // 返回 1
題解:
票選是在離散時間上發生的,每次更新只會對票數+1。 基于此,我們只需按照時間順序遍歷,找出每個時間點票數最高的人。
但由于時間是不連續的,最后給出任意一個時間點查詢時,我們還需要進行一次二分搜索。
找到到當前時間點最近的一次投票時間點,那個時候對應的最領先的候選人就是答案。
我將這套方法稱之為節點預處理。即不需要將每個值都預處理,只處理關鍵節點即可。
class TopVotedCandidate { private:vector<int> times;unordered_map<int, int>vis, res;int n;public:TopVotedCandidate(vector<int>& persons, vector<int>& times) {this->times = times;n = persons.size();int max_val = 0; // 保存當前最大的值for (int i = 0; i < n; ++i) {vis[persons[i]]++;if (vis[persons[i]] >= max_val) {max_val = vis[persons[i]];res[times[i]] = persons[i];} else {res[times[i]] = res[times[i-1]];}}}int q(int t) {int l = 0, r = n-1, m;while (l < r) {m = (l + r) / 2;if (times[m] == t) return res[times[m]];else if (t > times[m]) l = m+1;else r = m-1;}if (times[l] > t) return res[times[l-1]];else return res[times[l]];} };
總結
以上是生活随笔為你收集整理的【解题报告】Leecode911. 在线选举——Leecode每日一题系列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通俗易懂,CQRS概念浅析
- 下一篇: 【解题报告】Leecode 35. 搜索