这是我参与更文挑战的第4天,活动详情查看: 更文挑战
描述
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.
The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.
Return the earliest year with the maximum population.
Example 1:
Input: logs = [[1993,1999],[2000,2010]]
Output: 1993
Explanation: The maximum population is 1, and 1993 is the earliest year with this population.
Example 2:
Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
Explanation:
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
Note:
1 <= logs.length <= 100
1950 <= birthi < deathi <= 2050
解析
根据题意,就是找出人口最多最早的年份,我这边比较取巧,直接将 logs 遍历一次,将每个年份的人口都记录下来,然后找出最多人口的年份列表,经过排序找出最早的年份。
解答
class Solution(object):
def maximumPopulation(self, logs):
"""
:type logs: List[List[int]]
:rtype: int
"""
d = {}
for log in logs:
for i in range(log[0], log[1]):
if i not in d:
d[i] = 1
else:
d[i] += 1
a = [i for i in d.items() if i[1]==max(d.values())]
a.sort()
return a[0][0]
运行结果
Runtime: 36 ms, faster than 52.27% of Python online submissions for Maximum Population Year.
Memory Usage: 13.6 MB, less than 27.27% of Python online submissions for Maximum Population Year.
解析
这个是看到其他高手的答案,思路豁然开朗,就是将 logs 中每个元素变为元组添加到列表 datas 中,出生年变为 (出生年,1),去世年变为(去世年,-1),然后将 datas 根据年份排序,再遍历 datas ,遍历的元素 data[1] 为 1 即总人口加 1 ,data[1] 为 -1 即总人口减 1 ,如果计算之后的人口比历史人口多,就更新总人口和年份,遍历结束即可找到人口最多的最早的年份。
解答
class Solution(object):
def maximumPopulation(self, logs):
"""
:type logs: List[List[int]]
:rtype: int
"""
datas = []
for log in logs:
datas.append((log[0],1))
datas.append((log[1],-1))
population=history=year = 0
datas.sort()
for data in datas:
population += data[1]
if population > history:
history = population
year = data[0]
return year
运行结果
Runtime: 20 ms, faster than 97.73% of Python online submissions for Maximum Population Year.
Memory Usage: 13.5 MB, less than 27.27% of Python online submissions for Maximum Population Year.
原题链接:leetcode.com/problems/ma…
您的支持是我最大的动力