LeetCode 题解工作台
人员站位的方案数 I
给你一个 n x 2 的二维数组 points ,它表示二维平面上的一些点坐标,其中 points[i] = [x i , y i ] 。 计算点对 (A, B) 的数量,其中 A 在 B 的左上角,并且 它们形成的长方形中(或直线上)没有其它点( 包括边界 ),除了点 A 和点 B 。 返回数量。…
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们不妨考虑枚举矩形左上角的点 $(x_1, y_1)$,那么根据题目,右下角的点 $(x_2, y_2)$ 随着 的增大,纵坐标 也会要严格增大,才符合题意。 因此,我们对所有点按照 坐标升序排序,如果 坐标相同,按照 坐标降序排序。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个 n x 2 的二维数组 points ,它表示二维平面上的一些点坐标,其中 points[i] = [xi, yi] 。
计算点对 (A, B) 的数量,其中
A在B的左上角,并且- 它们形成的长方形中(或直线上)没有其它点(包括边界),除了点
A和点B。
返回数量。
示例 1:
输入:points = [[1,1],[2,2],[3,3]]
输出:0
解释:

没有办法选择 A 和 B,使得 A 在 B 的左上角。
示例 2:
输入:points = [[6,2],[4,4],[2,6]]
输出:2
解释:

- 左边的是点对
(points[1], points[0]),其中points[1]在points[0]的左上角,并且形成的长方形内部是空的。 - 中间的是点对
(points[2], points[1]),和左边的一样是合法的点对。 - 右边的是点对
(points[2], points[0]),其中points[2]在points[0]的左上角,但points[1]在长方形内部,所以不是一个合法的点对。
示例 3:
输入:points = [[3,1],[1,3],[1,1]]
输出:2
解释:

- 左边的是点对
(points[2], points[0]),其中points[2]在points[0]的左上角并且在它们形成的直线上没有其它点。注意两个点形成一条线的情况是合法的。 - 中间的是点对
(points[1], points[2]),和左边一样也是合法的点对。 - 右边的是点对
(points[1], points[0]),它不是合法的点对,因为points[2]在长方形的边上。
提示:
2 <= n <= 50points[i].length == 20 <= points[i][0], points[i][1] <= 50points[i]点对两两不同。
解题思路
方法一:排序 + 枚举
我们不妨考虑枚举矩形左上角的点 ,那么根据题目,右下角的点 随着 的增大,纵坐标 也会要严格增大,才符合题意。
因此,我们对所有点按照 坐标升序排序,如果 坐标相同,按照 坐标降序排序。
然后我们枚举左上角的点 ,并且维护一个最大的 ,记为 ,表示所有右下角的点的纵坐标的最大值。然后我们枚举右下角的点 ,如果 大于 并且小于等于 ,那么我们就找到了一个合法的方案,将答案加一,然后更新 为 。
枚举完所有的点对后,我们就得到了答案。
时间复杂度 ,空间复杂度 。其中 是点的数量。
class Solution:
def numberOfPairs(self, points: List[List[int]]) -> int:
points.sort(key=lambda x: (x[0], -x[1]))
ans = 0
for i, (_, y1) in enumerate(points):
max_y = -inf
for _, y2 in points[i + 1 :]:
if max_y < y2 <= y1:
max_y = y2
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) in the worst case due to double iteration over points, but acceptable for n <= 50. Space complexity is O(1) extra beyond input storage, unless using auxiliary arrays for sorting or counting. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Pay attention to correct inequality directions for upper-left vs lower-right pairs.
- question_mark
Consider how small constraints allow brute-force enumeration without performance penalty.
- question_mark
Sorting points by x or y may simplify counting but is optional for correctness.
常见陷阱
外企场景- error
Confusing upper-left with lower-left or upper-right positions when comparing coordinates.
- error
Counting the same pair twice due to symmetric iteration over points.
- error
Ignoring the strict inequality requirement in either x or y coordinates.
进阶变体
外企场景- arrow_right_alt
Count pairs with relaxed inequality, allowing A.x <= B.x and A.y >= B.y.
- arrow_right_alt
Find all triples of points forming a specific geometric shape using similar enumeration.
- arrow_right_alt
Extend to 3D coordinates, counting pairs where one point is strictly less in x and y but greater in z.