文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
1. Description
2. Solution
解析:Version 1逼龟,創(chuàng)建一個統(tǒng)計年份人數(shù)數(shù)組蝇闭,遍歷所有日志哪审,遍歷出生、死亡之間的年份丸边,累加對應年份的人口,最后找出人口最多最早的年份背镇,注意邊界值殿较。Version 2是遍歷所有年份,再遍歷所有日志澜躺,統(tǒng)計每個年份的人口并比較蝉稳,比Version 1要慢一些。Version 3根據(jù)出生年份和死亡年份來更新當年的人口變化掘鄙,出省年份人口數(shù)量加1
耘戚,死亡年份人口數(shù)量減1
,最后遍歷所有年份操漠,累加每個年份的人口變化即為當前年份的總人口收津,注意,此時2050年
死亡人口要減1
浊伙,因此邊界值要變?yōu)?code>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