Problem
You are given two integer arrays persons and times. In an election, the
ith vote was cast for persons[i] at time times[i].
For each query at a time t, find 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.
Implement the TopVotedCandidate class:
TopVotedCandidate(int[] persons, int[] times)Initializes the object with thepersonsandtimesarrays.int q(int t)Returns the number of the person that was leading the election at timetaccording to the mentioned rules.
Examples
Example 1
| |
Constraints
1 <= persons.length <= 5000times.length == persons.length0 <= persons[i] < persons.length0 <= times[i] <= 10^9timesis sorted in a strictly increasing order.times[0] <= t <= 10^9- At most
104calls will be made toq.
Solution
Method 1 – Prefix Leader Array + Binary Search
Intuition
We want to answer queries for the leader at any time t efficiently. By precomputing the leader after each vote, we can use binary search to quickly find the leader at any query time.
Approach
- In the constructor, iterate through the votes, keep a count for each person, and track the current leader after each vote. Store the leader at each time.
- For each query, use binary search to find the last time <= t, and return the leader at that time.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(log n)per query,O(n)for preprocessing, where n is the number of votes. - 🧺 Space complexity:
O(n), for storing leaders and times.