Leetcode 1854. Maximum Population Year

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1854. Maximum Population Year相关的知识,希望对你有一定的参考价值。

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

1. Description

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/

以上是关于Leetcode 1854. Maximum Population Year的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode1854. 人口最多的年份(C++)

[Leetcode] Maximum Subarray

[LeetCode]Maximum Subarray

#Leetcode# 53. Maximum Subarray

LeetCode 53. Maximum Subarray

LeetCode -- Maximum Product Subarray