LeetCode 题解工作台
人口最多的年份
给你一个二维整数数组 logs ,其中每个 logs[i] = [birth i , death i ] 表示第 i 个人的出生和死亡年份。 年份 x 的 人口 定义为这一年期间活着的人的数目。第 i 个人被计入年份 x 的人口需要满足: x 在闭区间 [birth i , death i - 1]…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们注意到,年份的范围是 ,因此我们可以将这些年份映射到一个长度为 的数组 中,数组的下标表示年份减去 的值。 接下来遍历 ,对于每个人,我们将 $d[birth_i - 1950]$ 加 ,将 $d[death_i - 1950]$ 减 。最后遍历数组 ,求出前缀和的最大值,即为人口最多的年份,再加上 即为答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个二维整数数组 logs ,其中每个 logs[i] = [birthi, deathi] 表示第 i 个人的出生和死亡年份。
年份 x 的 人口 定义为这一年期间活着的人的数目。第 i 个人被计入年份 x 的人口需要满足:x 在闭区间 [birthi, deathi - 1] 内。注意,人不应当计入他们死亡当年的人口中。
返回 人口最多 且 最早 的年份。
示例 1:
输入:logs = [[1993,1999],[2000,2010]] 输出:1993 解释:人口最多为 1 ,而 1993 是人口为 1 的最早年份。
示例 2:
输入:logs = [[1950,1961],[1960,1971],[1970,1981]] 输出:1960 解释: 人口最多为 2 ,分别出现在 1960 和 1970 。 其中最早年份是 1960 。
提示:
1 <= logs.length <= 1001950 <= birthi < deathi <= 2050
解题思路
方法一:差分数组
我们注意到,年份的范围是 ,因此我们可以将这些年份映射到一个长度为 的数组 中,数组的下标表示年份减去 的值。
接下来遍历 ,对于每个人,我们将 加 ,将 减 。最后遍历数组 ,求出前缀和的最大值,即为人口最多的年份,再加上 即为答案。
时间复杂度 ,空间复杂度 。其中 为数组 的长度;而 为年份的范围大小,即 。
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
d = [0] * 101
offset = 1950
for a, b in logs:
a, b = a - offset, b - offset
d[a] += 1
d[b] -= 1
s = mx = j = 0
for i, x in enumerate(d):
s += x
if mx < s:
mx, j = s, i
return j + offset
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate optimizes the approach by using a prefix sum technique.
- question_mark
Look for the candidate's ability to handle ties in population values.
- question_mark
Test if the candidate can efficiently count population using a simple array.
常见陷阱
外企场景- error
Not correctly handling the exclusive nature of death years.
- error
Forgetting to return the earliest year in case of ties in population counts.
- error
Using inefficient methods that do not optimize population tracking over a range of years.
进阶变体
外企场景- arrow_right_alt
Use a different method to track population changes, such as a hash map.
- arrow_right_alt
Consider a problem where some birth years are earlier than others, requiring a more complex population calculation.
- arrow_right_alt
Limit the input size and check how the candidate handles edge cases like maximum years in a small range.