LeetCode 911: Online Election Solution
Master LeetCode problem 911 (Online Election), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
911. Online Election
Problem Explanation
Explanation:
To solve this problem efficiently, we can use a HashMap to keep track of the number of votes each person has received at any given time. We will also maintain a TreeMap to store the total votes for each person at different times.
-
Constructor (TopVotedCandidate):
- Create a HashMap
votesCountto store the number of votes received by each person. - Create a TreeMap
winnersto store the total votes for each person at different times. - Iterate through the persons and times arrays to update the votesCount and winners maps.
- Create a HashMap
-
Query (q):
- Use the TreeMap floorEntry() method to find the entry with the largest time value less than or equal to the given time t.
- Return the person with the most votes at that time.
:
Solution Code
class TopVotedCandidate {
Map<Integer, Integer> votesCount;
TreeMap<Integer, Integer> winners;
public TopVotedCandidate(int[] persons, int[] times) {
votesCount = new HashMap<>();
winners = new TreeMap<>();
int maxVotes = 0;
int currentWinner = -1;
for (int i = 0; i < persons.length; i++) {
votesCount.put(persons[i], votesCount.getOrDefault(persons[i], 0) + 1);
int votes = votesCount.get(persons[i]);
if (votes >= maxVotes) {
maxVotes = votes;
currentWinner = persons[i];
}
winners.put(times[i], currentWinner);
}
}
public int q(int t) {
int time = winners.floorKey(t);
return winners.get(time);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 911 (Online Election)?
This page provides optimized solutions for LeetCode problem 911 (Online Election) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 911 (Online Election)?
The time complexity for LeetCode 911 (Online Election) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 911 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 911 in Java, C++, or Python.