Problem
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 1:
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].
解题思路
这一题的目的在与查找一个时间节点之前(或者正好是这个时间节点)的获票最高的人,因为查找操作需要运行很多次,因此,我们必须优化查找操作。如果使用从头到尾进行遍历的操作来查找是很费时间的。考虑到时间的升序排列,很容易想到的是二分查找。在这一块,C++语言已经进行了封装,直接调用即可。
解题的第一步就是计算每个时间节点对应的获票最高的人,并按照时间顺序保存在一个数组中。这一步是在构造函数中完成的。在查找的函数中,我们利用 l o w e r _ b o u n d lower\_bound lower_bound函数来在一个有序的数组中查找第一个大于或者等于查找值的数据,并返回一个迭代器。如果当前的迭代器为 e n d end end,说明没有数据可以大过需要查找的值,则返回最后一个获票最高的人即可。如果迭代器指向的值和需要查找的值相等,在获取最高票数的人的数组中直接找到对应位置的人,返回即可。如果迭代器指向的值大于需要查找的值,则当前迭代器前一个值才是正确的需要的数据,因此,迭代器减一,并返回相应的人。
代码如下:
class candidate
{
public:
int count;
int time;
};
class TopVotedCandidate {
public:
vector<int> time;
vector<int> leading;
TopVotedCandidate(vector<int>& persons, vector<int>& times)
{
int num = *max_element(persons.begin(), persons.end()) + 1;
time = times;
vector<candidate> cands(num);
for (size_t i = 0; i < times.size(); ++i)
{
cands[persons[i]].count += 1;
cands[persons[i]].time = times[i];
int pos = 0;
for (size_t j = 1; j < cands.size(); ++j)
{
if (cands[j].count > cands[pos].count ||
(cands[j].count == cands[pos].count && cands[j].time > cands[pos].time))
{
pos = j;
}
}
leading.push_back(pos);
}
}
int q(int t)
{
auto p = lower_bound(time.begin(), time.end(), t);
if (p == time.end())
{
return leading.back();
}
if (*p == t)
{
return leading[p - time.begin()];
}
if (*p > t)
{
return leading[(p - 1) - time.begin()];
}
return 0;
}
};
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate* obj = new TopVotedCandidate(persons, times);
* int param_1 = obj->q(t);
*/