当前位置: 代码迷 >> 综合 >> Leetcode 1854. Maximum Population Year
  详细解决方案

Leetcode 1854. Maximum Population Year

热度:31   发布时间:2023-12-12 20:51:13.0

文章作者: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 = 1950end = 2050stat = [0] * (end - start)for birth, death in logs:for i in range(birth, death):stat[i - start] += 1temp = 0for index, count in enumerate(stat):if count > temp:result = indextemp = countreturn result + start
  • Version 2
class Solution:def maximumPopulation(self, logs: List[List[int]]) -> int:start = 1950end = 2050temp = 0for i in range(start, end):count = 0for birth, death in logs: if birth <= i and i < death:count += 1if count > temp:temp = countresult = ireturn result
  • Version 3
class Solution:def maximumPopulation(self, logs: List[List[int]]) -> int:start = 1950end = 2050stat = [0] * (end - start + 1)for birth, death in logs:stat[birth - start] += 1stat[death - start] -= 1temp = 0current = 0for index, count in enumerate(stat):current += countif current > temp:result = indextemp = currentreturn result + start

Reference

  1. https://leetcode.com/problems/maximum-population-year/
  相关解决方案