|
| 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