LeetCode 题解工作台

人口最多的年份

给你一个二维整数数组 logs ,其中每个 logs[i] = [birth i , death i ] 表示第 i 个人的出生和死亡年份。 年份 x 的 人口 定义为这一年期间活着的人的数目。第 i 个人被计入年份 x 的人口需要满足: x 在闭区间 [birth i , death i - 1]…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 前缀和

bolt

答案摘要

我们注意到,年份的范围是 ,因此我们可以将这些年份映射到一个长度为 的数组 中,数组的下标表示年份减去 的值。 接下来遍历 ,对于每个人,我们将 $d[birth_i - 1950]$ 加 ,将 $d[death_i - 1950]$ 减 。最后遍历数组 ,求出前缀和的最大值,即为人口最多的年份,再加上 即为答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二维整数数组 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 <= 100
  • 1950 <= birthi < deathi <= 2050
lightbulb

解题思路

方法一:差分数组

我们注意到,年份的范围是 [1950,..2050][1950,..2050],因此我们可以将这些年份映射到一个长度为 101101 的数组 dd 中,数组的下标表示年份减去 19501950 的值。

接下来遍历 logslogs,对于每个人,我们将 d[birthi1950]d[birth_i - 1950]11,将 d[deathi1950]d[death_i - 1950]11。最后遍历数组 dd,求出前缀和的最大值,即为人口最多的年份,再加上 19501950 即为答案。

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 为数组 logslogs 的长度;而 CC 为年份的范围大小,即 20501950+1=1012050 - 1950 + 1 = 101

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

人口最多的年份题解:前缀和 | LeetCode #1854 简单