栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣每日一题2021-12-11在线选举

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣每日一题2021-12-11在线选举

在线选举
  • 911.在线选举
    • 题目描述
    • 思路
      • 二分查找
        • Java实现
        • Python实现


911.在线选举 题目描述

在线选举


思路 二分查找

因为是在线查询,因此在初始化时就统计所有投票时刻的计票结果,如果查询投票时刻之间的时刻,则答案就是上一个投票时刻的答案。

Java实现

class TopVotedCandidate {
    private int[] times;
    private int[] ans;
    public TopVotedCandidate(int[] persons, int[] times) {
        this.times = times;
        ans = new int[times.length];
        int[] cnts = new int[times.length];
        int cur = -1;
        for(int i=0;i= cnts[cur])
                cur = persons[i];
            ans[i] = cur;
        }
    }
    
    public int q(int t) {
        int l = 0, r = times.length;
        while(l 
Python实现 

class TopVotedCandidate:

    def __init__(self, persons: List[int], times: List[int]):
        n = len(times)
        cnts, cur = defaultdict(int), None
        self.ans, self.times = [-1] * n, times
        for i in range(n):
            cnts[persons[i]] += 1
            if cur is None or cnts[persons[i]] >= cnts[cur]:
                cur = persons[i]
            self.ans[i] = cur


    def q(self, t: int) -> int:
        return self.ans[bisect_right(self.times, t) - 1]



# Your TopVotedCandidate object will be instantiated and called as such:
# obj = TopVotedCandidate(persons, times)
# param_1 = obj.q(t)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/657333.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号