Leetcode 1854. Maximum Population Year

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximum Population Year

2. Solution

**解析:**Version 1,创建一个统计年份人数数组,遍历所有日志,遍历出生、死亡之间的年份,累加对应年份的人口,最后找出人口最多最早的年份,注意边界值。Version 2是遍历所有年份,再遍历所有日志,统计每个年份的人口并比较,比Version 1要慢一些。Version 3根据出生年份和死亡年份来更新当年的人口变化,出省年份人口数量加1,死亡年份人口数量减1,最后遍历所有年份,累加每个年份的人口变化即为当前年份的总人口,注意,此时2050年死亡人口要减1,因此边界值要变为end - start + 1

  • Version 1
class Solution:
    def maximumPopulation(self, logs: List[List[int]]) -> int:
        start = 1950
        end = 2050
        stat = [0] * (end - start)
        for birth, death in logs:
            for i in range(birth, death):
                stat[i - start] += 1
        temp = 0
        for index, count in enumerate(stat):
            if count > temp:
                result = index
                temp = count
        return result + start
  • Version 2
class Solution:
    def maximumPopulation(self, logs: List[List[int]]) -> int:
        start = 1950
        end = 2050
        temp = 0
        for i in range(start, end):
            count = 0
            for birth, death in logs: 
                if birth <= i and i < death:
                    count += 1
            if count > temp:
                temp = count
                result = i
        return result
  • Version 3
class Solution:
    def maximumPopulation(self, logs: List[List[int]]) -> int:
        start = 1950
        end = 2050
        stat = [0] * (end - start + 1)
        for birth, death in logs:
            stat[birth - start] += 1
            stat[death - start] -= 1
        temp = 0
        current = 0
        for index, count in enumerate(stat):
            current += count
            if current > temp:
                result = index
                temp = current
        return result + start

Reference

  1. https://leetcode.com/problems/maximum-population-year/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值