返回介绍

solution / 2500-2599 / 2579.Count Total Number of Colored Cells / README_EN

发布于 2024-06-17 01:03:04 字数 3095 浏览 0 评论 0 收藏 0

2579. Count Total Number of Colored Cells

中文文档

Description

There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes:

  • At the first minute, color any arbitrary unit cell blue.
  • Every minute thereafter, color blue every uncolored cell that touches a blue cell.

Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.

Return _the number of colored cells at the end of _n _minutes_.

 

Example 1:

Input: n = 1
Output: 1
Explanation: After 1 minute, there is only 1 blue cell, so we return 1.

Example 2:

Input: n = 2
Output: 5
Explanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. 

 

Constraints:

  • 1 <= n <= 105

Solutions

Solution 1: Mathematics

We find that after the $n$th minute, there are a total of $2 \times n - 1$ columns in the grid, and the numbers on each column are respectively $1, 3, 5, \cdots, 2 \times n - 1, 2 \times n - 3, \cdots, 3, 1$. The left and right parts are both arithmetic progressions, and the sum can be obtained by $2 \times n \times (n - 1) + 1$.

The time complexity is $O(1)$, and the space complexity is $O(1)$.

class Solution:
  def coloredCells(self, n: int) -> int:
    return 2 * n * (n - 1) + 1
class Solution {
  public long coloredCells(int n) {
    return 2L * n * (n - 1) + 1;
  }
}
class Solution {
public:
  long long coloredCells(int n) {
    return 2LL * n * (n - 1) + 1;
  }
};
func coloredCells(n int) int64 {
  return int64(2*n*(n-1) + 1)
}
function coloredCells(n: number): number {
  return 2 * n * (n - 1) + 1;
}
impl Solution {
  pub fn colored_cells(n: i32) -> i64 {
    2 * (n as i64) * ((n as i64) - 1) + 1
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文