LeetCode 911. Online Election

版权声明:码字不易,转载请注明出处: https://blog.csdn.net/qq_24309981/article/details/90266922

1 描述

Description

  • In an election, the i-th vote was cast for persons[i] at time times[i].
  • Now, we would like to implement the following query function: TopVotedCandidate.q(int t) will return the number of the person that was leading the election at time t.
  • Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.

Example

  • Input: [“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]]
  • Output: [null,0,1,1,0,0,1]
  • Explanation:
    At time 3, the votes are [0], and 0 is leading.
    At time 12, the votes are [0,1,1], and 1 is leading.
    At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)
    This continues for 3 more queries at time 15, 24, and 8.

Note

  • 1 <= persons.length = times.length <= 5000
  • 0 <= persons[i] <= persons.length
  • times is a strictly increasing array with all elements in [0, 10^9].
  • TopVotedCandidate.q is called at most 10000 times per test case.
  • TopVotedCandidate.q(int t) is always called with t >= times[0].

2 代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

class TopVotedCandidate {
public:
	//(time,leader)
	vector<pair<int, int>> tLeader;
	TopVotedCandidate(vector<int>& persons, vector<int>& times) {
		//(person, votes)
		unordered_map<int, int> pVote;
		int maxVote = 0;
		for (int i = 0; i < times.size(); i++)
		{
			pVote[persons[i]]++;
			if (pVote[persons[i]] >= maxVote)
			{
				maxVote = pVote[persons[i]];
				tLeader.push_back(pair<int, int>(times[i], persons[i]));
			}
			//there is no need "else"
		}
	}

	int q(int t) {
		auto it = upper_bound(tLeader.begin(), tLeader.end(), pair<int, int>(t, 5000));
		it--;
		return it->second;
	}
};

int main()
{
	/*vector<int> persons = { 0,1,1,0,0,1,0 };
	vector<int> times = { 0,5,10,15,20,25,30 };*/
	vector<int> persons = { 0, 1};
	vector<int> times = { 0, 2 };
	TopVotedCandidate tv(persons, times);
	int leader = tv.q(3);
	cout << leader << endl;
	leader = tv.q(12);
	cout << leader << endl;
	leader = tv.q(25);
	cout << leader << endl;
	leader = tv.q(15);
	cout << leader << endl;
	leader = tv.q(24);
	cout << leader << endl;
	leader = tv.q(8);
	cout << leader << endl;
	system("pause");
    return 0;
}

3 解释

按照时间统计每个候选人的得票数;

  • 每个候选人出现一次,则其对应投票数加一;

记录每个时间节点,who is leading:

  • 如果某个候选人的票数,大于等于当前最高得票数(为什么要等于:ties go to the most recent vote),并将该候选人作为当前时间节点的 “获得票数最多的人(it is leading)”;
  • 当某个候选人在多个连续时间节点上均保持票数领先,则只需记录其第一次成为票数最多人的时间节点,而不对后序时间节点进行记录。

猜你喜欢

转载自blog.csdn.net/qq_24309981/article/details/90266922