LeetCode(在线选举)

654 阅读1分钟

在线选举

image.png

题目分析

  • 根据题意我们需要统计在tt时刻获得选票最多的候选人,这里我们对数据进行预处理,在每次增加选票时记录当前的最高票数与候选人idid,如果获得选票最多的候选人发生变化我们向sourcesource中插入当前时间加候选人idid的信息。在每次查询tt时刻获得选票最多的候选人时,我们用二分法对sourcesource进行查询,查找第一个<=t<=t时间的信息。

代码

/**
 * @param {number[]} persons
 * @param {number[]} times
 */
let TopVotedCandidate = function (persons, times) {
  const map = new Map();
  let max = -1;
  this.source = [];
  for (let i = 0, { length } = times; i < length; ++i) {
    let v = map.get(persons[i]) || 0;
    if (++v >= max) {
      this.source.push({ time: times[i], id: persons[i] });
      max = v;
    }
    map.set(persons[i], v);
  }
};

/**
 * @param {number} t
 * @return {number}
 */
TopVotedCandidate.prototype.q = function (t) {
  const { source } = this;
  let left = 0;
  let right = source.length - 1;
  while (left <= right) {
    let mid = left + ((right - left) >> 1);
    if (source[mid].time < t) {
      left = mid + 1;
    } else if (source[mid].time > t) {
      right = mid - 1;
    } else {
      return source[mid].id;
    }
  }
  return source[right].id;
};

/**
 * Your TopVotedCandidate object will be instantiated and called as such:
 * var obj = new TopVotedCandidate(persons, times)
 * var param_1 = obj.q(t)
 */