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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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/
如果有收获,可以请我喝杯咖啡!