面试题 16.10. 生存人数
class Solution { public: int maxAliveYear(vector<int>& birth, vector<int>& death) { int ans = 0, length = birth.size(); vector<int> cnt(105,0); for(int i = 0; i < length; i++){ cnt[birth[i] - 1900]++; cnt[death[i] - 1900 + 1]--; } int preSum = 0, maxLive = 0; for(int i = 0; i < 105; i++){ preSum += cnt[i]; // 前缀和/累加 if(preSum > maxLive){ maxLive = preSum; ans = i; } } return ans + 1900; } };
class Solution: def maxAliveYear(self, birth: List[int], death: List[int]) -> int: birth_total = [0 for _ in range(105)] death_total = [0 for _ in range(105)] length = len(birth) # 记录这100年每年出生和死亡的人数 for i in range(length): birth_total[birth[i] - 1900] += 1 death_total[death[i] - 1900 + 1] += 1 # 记录这100年每年累计出生和累计死亡的人数 for i in range(1,101): birth_total[i] += birth_total[i - 1] death_total[i] += death_total[i - 1] live = 0 for i in range(101): #print(birth_total[i] - death_total[i], live, i + 1900) if birth_total[i] - death_total[i] > live: live = birth_total[i] - death_total[i] re = i + 1900 return re
我是傻逼…没好好审题,手动调试了1个小时,1909年死亡的人在1909年是计数的…