面试题 16.10. 生存人数

给定N个人的出生年份和死亡年份,第i个人的出生年份为birth[i],死亡年份为death[i],实现一个方法以计算生存人数最多的年份。

你可以假设所有人都出生于1900年至2000年(含1900和2000)之间。如果一个人在某一年的任意时期都处于生存状态,那么他们应该被纳入那一年的统计中。例如,生于1908年、死于1909年的人应当被列入1908年和1909年的计数。如果有多个年份生存人数相同且均为最大值,输出其中最小的年份。

示例:

输入:
birth = {1900, 1901, 1950}
death = {1948, 1951, 2000}
输出: 1901

思路:用一个字典map存放birth和death出现的最小和最大年份之间的所有年份的生存人数。map的key为年份,value为生存人数。注意map最后要按年份排序,然后返回value最大的key。

class Solution:
    def maxAliveYear(self, birth: List[int], death: List[int]) -> int:
        l_map = {}
        for i in range(len(birth)):
            for j in range(birth[i],death[i]+1):
                if j not in l_map:
                    l_map[j]=0
                l_map[j]+=1
        l_items=sorted(l_map.items(),key=lambda item:item[0])
        max_year = 1900
        max_count = 0
        for k,v in l_items:
            if v>max_count:
                max_count=v
                max_year=k
        return max_year

链接:https://leetcode-cn.com/problems/living-people-lcci/solution/python-mapjie-jue-shuang-100-by-fastcode3d/

原文地址:https://www.cnblogs.com/USTC-ZCC/p/12886673.html