Skip to content

Commit 75ccaa8

Browse files
committedMar 24, 2025
Add solution #911
1 parent 147f4c0 commit 75ccaa8

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,7 @@
721721
908|[Smallest Range I](./solutions/0908-smallest-range-i.js)|Easy|
722722
909|[Snakes and Ladders](./solutions/0909-snakes-and-ladders.js)|Medium|
723723
910|[Smallest Range II](./solutions/0910-smallest-range-ii.js)|Medium|
724+
911|[Online Election](./solutions/0911-online-election.js)|Medium|
724725
912|[Sort an Array](./solutions/0912-sort-an-array.js)|Medium|
725726
914|[X of a Kind in a Deck of Cards](./solutions/0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium|
726727
916|[Word Subsets](./solutions/0916-word-subsets.js)|Medium|

‎solutions/0911-online-election.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* 911. Online Election
3+
* https://leetcode.com/problems/online-election/
4+
* Difficulty: Medium
5+
*
6+
* You are given two integer arrays persons and times. In an election, the ith vote was cast for
7+
* persons[i] at time times[i].
8+
*
9+
* For each query at a time t, find the person that was leading the election at time t. Votes
10+
* cast at time t will count towards our query. In the case of a tie, the most recent vote (among
11+
* tied candidates) wins.
12+
*
13+
* Implement the TopVotedCandidate class:
14+
* - TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and
15+
* times arrays.
16+
* - int q(int t) Returns the number of the person that was leading the election at time t according
17+
* to the mentioned rules.
18+
*/
19+
20+
/**
21+
* @param {number[]} persons
22+
* @param {number[]} times
23+
*/
24+
var TopVotedCandidate = function(persons, times) {
25+
this.times = times;
26+
this.leaders = [];
27+
const voteCount = new Map();
28+
let maxVotes = 0;
29+
let currentLeader = 0;
30+
31+
for (let i = 0; i < persons.length; i++) {
32+
const votes = (voteCount.get(persons[i]) || 0) + 1;
33+
voteCount.set(persons[i], votes);
34+
35+
if (votes >= maxVotes) {
36+
maxVotes = votes;
37+
currentLeader = persons[i];
38+
}
39+
this.leaders[i] = currentLeader;
40+
}
41+
};
42+
43+
/**
44+
* @param {number} t
45+
* @return {number}
46+
*/
47+
TopVotedCandidate.prototype.q = function(t) {
48+
let left = 0;
49+
let right = this.times.length - 1;
50+
51+
while (left <= right) {
52+
const middle = Math.floor((left + right) / 2);
53+
if (this.times[middle] <= t) {
54+
left = middle + 1;
55+
} else {
56+
right = middle - 1;
57+
}
58+
}
59+
60+
return this.leaders[right];
61+
};

0 commit comments

Comments
 (0)
Please sign in to comment.