LeetCode 题解工作台

统计染色格子数

有一个无穷大的二维网格图,一开始所有格子都未染色。给你一个正整数 n ,表示你需要执行以下步骤 n 分钟: 第一分钟,将 任一 格子染成蓝色。 之后的每一分钟,将与蓝色格子相邻的 所有 未染色格子染成蓝色。 下图分别是 1、2、3 分钟后的网格图。 请你返回 n 分钟之后 被染色的格子 数目。 示例…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·driven

bolt

答案摘要

我们观察发现,第 分钟后,网格中共有 $2 \times n - 1$ 列,每一列上的数字分别为 $1, 3, 5, \cdots, 2 \times n - 1, 2 \times n - 3, \cdots, 3, 1$。左右两部分均为等差数列,求和可以得到答案 $2 \times n \times (n - 1) + 1$。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一个无穷大的二维网格图,一开始所有格子都未染色。给你一个正整数 n ,表示你需要执行以下步骤 n 分钟:

  • 第一分钟,将 任一 格子染成蓝色。
  • 之后的每一分钟,将与蓝色格子相邻的 所有 未染色格子染成蓝色。

下图分别是 1、2、3 分钟后的网格图。

请你返回 n 分钟之后 被染色的格子 数目。

 

示例 1:

输入:n = 1
输出:1
解释:1 分钟后,只有 1 个蓝色的格子,所以返回 1 。

示例 2:

输入:n = 2
输出:5
解释:2 分钟后,有 4 个在边缘的蓝色格子和 1 个在中间的蓝色格子,所以返回 5 。

 

提示:

  • 1 <= n <= 105
lightbulb

解题思路

方法一:数学

我们观察发现,第 nn 分钟后,网格中共有 2×n12 \times n - 1 列,每一列上的数字分别为 1,3,5,,2×n1,2×n3,,3,11, 3, 5, \cdots, 2 \times n - 1, 2 \times n - 3, \cdots, 3, 1。左右两部分均为等差数列,求和可以得到答案 2×n×(n1)+12 \times n \times (n - 1) + 1

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def coloredCells(self, n: int) -> int:
        return 2 * n * (n - 1) + 1
speed

复杂度分析

指标
时间O(1)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate should demonstrate an ability to recognize mathematical patterns and derive efficient formulas.

  • question_mark

    Look for clarity in explaining the relation between n and the total colored cells.

  • question_mark

    Check if the candidate is able to explain how constant time complexity is achieved in this solution.

warning

常见陷阱

外企场景
  • error

    Candidates might confuse the total number of colored cells with a simpler linear growth pattern, missing the quadratic nature.

  • error

    Over-complicating the problem by trying to simulate the grid's growth instead of using a direct formula.

  • error

    Failure to recognize that the problem can be solved in constant time may lead to inefficient solutions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to include a constraint on the grid size, limiting the total number of colored cells after n minutes.

  • arrow_right_alt

    Ask the candidate to calculate the total number of colored cells after k minutes given multiple values of n.

  • arrow_right_alt

    Extend the problem to handle multiple grids and calculate the total number of colored cells across several test cases.

help

常见问题

外企场景

统计染色格子数题解:数学·driven | LeetCode #2579 中等