LeetCode 题解工作台

统计圆内格点数目

给你一个二维整数数组 circles ,其中 circles[i] = [x i , y i , r i ] 表示网格上圆心为 (x i , y i ) 且半径为 r i 的第 i 个圆,返回出现在 至少一个 圆内的 格点数目 。 注意: 格点 是指整数坐标对应的点。 圆周上的点 也被视为出现在圆内…

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

枚举所有的格点,判断其是否在圆内,如果在圆内,则答案加一。 枚举的时候,可以将所有圆的最大横纵坐标求出来,作为枚举的上界。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二维整数数组 circles ,其中 circles[i] = [xi, yi, ri] 表示网格上圆心为 (xi, yi) 且半径为 ri 的第 i 个圆,返回出现在 至少一个 圆内的 格点数目

注意:

  • 格点 是指整数坐标对应的点。
  • 圆周上的点 也被视为出现在圆内的点。

 

示例 1:

输入:circles = [[2,2,1]]
输出:5
解释:
给定的圆如上图所示。
出现在圆内的格点为 (1, 2)、(2, 1)、(2, 2)、(2, 3) 和 (3, 2),在图中用绿色标识。
像 (1, 1) 和 (1, 3) 这样用红色标识的点,并未出现在圆内。
因此,出现在至少一个圆内的格点数目是 5 。

示例 2:

输入:circles = [[2,2,2],[3,4,1]]
输出:16
解释:
给定的圆如上图所示。
共有 16 个格点出现在至少一个圆内。
其中部分点的坐标是 (0, 2)、(2, 0)、(2, 4)、(3, 2) 和 (4, 4) 。

 

提示:

  • 1 <= circles.length <= 200
  • circles[i].length == 3
  • 1 <= xi, yi <= 100
  • 1 <= ri <= min(xi, yi)
lightbulb

解题思路

方法一:枚举

枚举所有的格点,判断其是否在圆内,如果在圆内,则答案加一。

枚举的时候,可以将所有圆的最大横纵坐标求出来,作为枚举的上界。

时间复杂度 O(X×Y×n)O(X \times Y \times n),空间复杂度 O(1)O(1)。其中 XXYY 分别为所有圆的最大横纵坐标,而 nn 为圆的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def countLatticePoints(self, circles: List[List[int]]) -> int:
        ans = 0
        mx = max(x + r for x, _, r in circles)
        my = max(y + r for _, y, r in circles)
        for i in range(mx + 1):
            for j in range(my + 1):
                for x, y, r in circles:
                    dx, dy = i - x, j - y
                    if dx * dx + dy * dy <= r * r:
                        ans += 1
                        break
        return ans
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Ability to optimize array scanning and hash lookups.

  • question_mark

    Focus on counting unique lattice points across multiple circles.

  • question_mark

    Understanding of geometric relationships between points and circles.

warning

常见陷阱

外企场景
  • error

    Failing to ensure points inside multiple circles are counted only once.

  • error

    Overlooking the need to check multiple circles for each point.

  • error

    Not optimizing the range of points to check, leading to excessive computation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count lattice points inside multiple circles with different sizes.

  • arrow_right_alt

    Consider dynamic radius or center changes for each circle.

  • arrow_right_alt

    Extend the problem to consider other geometric shapes, like ellipses.

help

常见问题

外企场景

统计圆内格点数目题解:数组·哈希·扫描 | LeetCode #2249 中等