def__init__(self, persons: List[int], times: List[int]): tops = [] voteCounts = defaultdict(int) voteCounts[-1] = -1 top = -1 for p in persons: voteCounts[p] += 1 if voteCounts[p] >= voteCounts[top]: top = p tops.append(top) self.tops = tops self.times = times defq(self, t: int) -> int: l, r = 0, len(self.times) - 1 # 找到满足 times[l] <= t 的最大的 l while l < r: m = l + (r - l + 1) // 2 if self.times[m] <= t: l = m else: r = m - 1 # 也可以使用内置的二分查找的包来确定 l # l = bisect.bisect(self.times, t) - 1 return self.tops[l]
publicTopVotedCandidate(int[] persons, int[] times) { tops = new List<int>(); voteCounts = new Dictionary<int, int>(); voteCounts.Add(-1, -1); int top = -1; for (int i = 0; i < persons.Length; ++i) { int p = persons[i]; if (!voteCounts.ContainsKey(p)) { voteCounts.Add(p, 0); } else { ++voteCounts[p]; } if (voteCounts[p] >= voteCounts[top]) { top = p; } tops.Add(top); } this.times = times; } publicintQ(int t) { int l = 0, r = times.Length - 1; // 找到满足 times[l] <= t 的最大的 l while (l < r) { int m = l + (r - l + 1) / 2; if (times[m] <= t) { l = m; } else { r = m - 1; } } return tops[l]; } }
varTopVotedCandidate = function(persons, times) { this.tops = []; this.voteCounts = newMap(); this.voteCounts.set(-1, -1); this.times = times; let top = -1; for (let i = 0; i < persons.length; ++i) { const p = persons[i]; if (!this.voteCounts.has(p)) { this.voteCounts.set(p, 0); } else { this.voteCounts.set(p, this.voteCounts.get(p) + 1); } if (this.voteCounts.get(p) >= this.voteCounts.get(top)) { top = p; } this.tops.push(top); } };
TopVotedCandidate.prototype.q = function(t) { let l = 0, r = this.times.length - 1; // 找到满足 times[l] <= t 的最大的 l while (l < r) { const m = l + Math.floor((r - l + 1) / 2); if (this.times[m] <= t) { l = m; } else { r = m - 1; } }
typedefstruct { int * tops; int * times; int timesSize; } TopVotedCandidate;
TopVotedCandidate* topVotedCandidateCreate(int* persons, int personsSize, int* times, int timesSize) { if (NULL == persons || NULL == times || persons <= 0 || timesSize <= 0) { returnNULL; }
TopVotedCandidate * obj = (TopVotedCandidate *)malloc(sizeof(TopVotedCandidate)); int * voteCounts = (int *)malloc(sizeof(int) * personsSize); memset(voteCounts, 0 ,sizeof(int) * personsSize); obj->timesSize = timesSize; obj->tops = (int *)malloc(sizeof(int) * personsSize); obj->times = (int *)malloc(sizeof(int) * timesSize); int top = -1; for (int i = 0; i < personsSize; ++i) { voteCounts[persons[i]]++; if (top < 0 || voteCounts[persons[i]] >= voteCounts[top]) { top = persons[i]; } obj->tops[i] = top; } for (int i = 0; i < timesSize; ++i) { obj->times[i] = times[i]; } free(voteCounts); return obj; }
inttopVotedCandidateQ(TopVotedCandidate* obj, int t) { if (NULL == obj) { return-1; } int l = 0, r = obj->timesSize - 1; while (l < r) { int m = l + (r - l + 1) / 2; if (obj->times[m] <= t) { l = m; } else { r = m - 1; } } return obj->tops[l]; }