911 Online Election
911. Online Election
1. Question
In an election, thei-th vote was cast forpersons[i]at timetimes[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 timet.
Votes cast at timetwill 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 <= 50000 <= persons[i] <= persons.lengthtimesis a strictly increasing array with all elements in[0, 10^9].TopVotedCandidate.qis called at most10000times per test case.TopVotedCandidate.q(int t)is always called witht >= times[0].
2. Implementation
(1) HashMap + Binary Search
思路: 对于给定times数组,我们需要做的就是对于times数组里每个对应的时间点,找到对应的winner是谁,这个可以直接用hashmap完成。而对于调用q()这个函数时,我们需要知道的是,对于任意的时刻t,我们要根据我们已知的times数组上的时间,用二分法找到不大于t的最大的时间。
3. Time & Space Complexity
HashMap + Binary Search: 时间复杂度: Constructor O(n), q(): O(logn), n是输入数组persons的长度,即人数。空间复杂度: O(n)
Last updated
Was this helpful?