【我也想刷穿 LeetCode啊】911. 在线选举

96 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

现在前端很多岗位面试需要有一定的算法基础,或者说经常刷算法的会优先考虑。

因此每天刷刷LeetCode非常有必要

在这之前我也刷过一些算法题,也希望以后也坚持刷,跟某掘友一样,我也想刷穿 LeetCode

一、题目描述

给你两个整数数组 persons 和 times 。在选举中,第 i 张票是在时刻为 times[i] 时投给候选人 persons[i] 的。

对于发生在时刻 t 的每个查询,需要找出在 t 时刻在选举中领先的候选人的编号。

在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。

实现 TopVotedCandidate 类:

  • TopVotedCandidate(int[] persons, int[] times) 使用 persons 和 times 数组初始化对象。
  • int q(int t) 根据前面描述的规则,返回在时刻 t 在选举中领先的候选人的编号。

二、思路分析

times非递减

预处理times每个时间点对应领先的那个人是谁的数组top

因为times非递减,upper_bound找query(t) 那个严格大于t的点是谁 然后top[这个点-1]就是当前时间t领先的那个人

三、代码实现

/**
 * @param {number[]} persons
 * @param {number[]} times
 */
var TopVotedCandidate = function(persons, times) {
    this.times = times;
    let map = {};
    let maxNum = 0;
    let maxPersion = -1;
    let top = [];
    for (let i = 0; i < persons.length; i++) {
        map[persons[i]] = map[persons[i]] || 0;
        map[persons[i]] ++;
        if (map[persons[i]] >= maxNum) {
            maxNum = map[persons[i]]
            maxPersion = persons[i];
        }
        top[i] = maxPersion;
    }
    // console.log(top);
    this.top = top;
};

/** 
 * @param {number} t
 * @return {number}
 */
// upper_bound
TopVotedCandidate.prototype.q = function(t) {
    let arr = this.times;
    // 左闭右开 不想特判 
    arr.push(Infinity);
    let l = 0;
    let r = arr.length - 1;
    while (l < r) {
        let mid = (l + r) >> 1;
         if (arr[mid] > t) {
             r = mid;
         } else {
             l = mid + 1;
         }
    }
    l = l - 1;
    return this.top[l];
};


四、总结

以上就是本道题的所有内容了,本系列会持续更,欢迎点赞、关注、收藏,另外如有其他的问题,欢迎下方留言给我,我会第一时间回复你,感谢~