网站建设市场行情分析,龙岩网络营销平台,可以发外链的平台,做网页的网站素材文章目录1. 题目2. 解题2.1 超时2.1 改进1. 题目
给你一个在 X-Y 平面上的点构成的数据流。设计一个满足下述要求的算法#xff1a;
添加 一个在数据流中的新点到某个数据结构中。可以添加 重复 的点#xff0c;并会视作不同的点进行处理。给你一个查询点#xff0c;请你从…
文章目录1. 题目2. 解题2.1 超时2.1 改进1. 题目
给你一个在 X-Y 平面上的点构成的数据流。设计一个满足下述要求的算法
添加 一个在数据流中的新点到某个数据结构中。可以添加 重复 的点并会视作不同的点进行处理。给你一个查询点请你从数据结构中选出三个点使这三个点和查询点一同构成一个 面积为正 的 轴对齐正方形 统计 满足该要求的方案数目。
轴对齐正方形 是一个正方形除四条边长度相同外还满足每条边都与 x-轴 或 y-轴 平行或垂直。
实现 DetectSquares 类
DetectSquares() 使用空数据结构初始化对象void add(int[] point) 向数据结构添加一个新的点 point [x, y]int count(int[] point) 统计按上述方式与点 point [x, y] 共同构造 轴对齐正方形 的方案数。
示例
输入
[DetectSquares, add, add, add, count, count, add, count]
[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]
输出
[null, null, null, null, 1, 0, null, 2]解释
DetectSquares detectSquares new DetectSquares();
detectSquares.add([3, 10]);
detectSquares.add([11, 2]);
detectSquares.add([3, 2]);
detectSquares.count([11, 10]); // 返回 1 。你可以选择// - 第一个第二个和第三个点
detectSquares.count([14, 8]); // 返回 0 。查询点无法与数据结构中的这些点构成正方形。
detectSquares.add([11, 2]); // 允许添加重复的点。
detectSquares.count([11, 10]); // 返回 2 。你可以选择// - 第一个第二个和第三个点// - 第一个第三个和第四个点提示
point.length 2
0 x, y 1000
调用 add 和 count 的 总次数 最多为 5000来源力扣LeetCode 链接https://leetcode-cn.com/problems/detect-squares 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。 2. 解题
2.1 超时
50 / 51 个通过测试用例
class DetectSquares:def __init__(self):self.x {}self.y {}self.p {}def add(self, point: List[int]) - None:if (point[0], point[1]) not in self.p:self.p[(point[0], point[1])] 1else:self.p[(point[0], point[1])] 1if point[0] not in self.x:self.x[point[0]] [(point[0], point[1])]else:self.x[point[0]].append((point[0], point[1]))if point[1] not in self.y:self.y[point[1]] [(point[0], point[1])]else:self.y[point[1]].append((point[0], point[1]))def count(self, point: List[int]) - int:ans 0if point[0] in self.x and point[1] in self.y:for xp in self.x[point[0]]:if xp[1] point[1]:continued abs(xp[1]-point[1])for yp in self.y[point[1]]:if yp[0] point[0]:continueif abs(yp[0]-point[0])d and (yp[0], xp[1]) in self.p:ans self.p[(yp[0], xp[1])]return ans2.1 改进
枚举对角线的另一点
class DetectSquares:def __init__(self):self.p {}def add(self, point: List[int]) - None:if (point[0], point[1]) not in self.p:self.p[(point[0], point[1])] 1else:self.p[(point[0], point[1])] 1def count(self, point: List[int]) - int:ans 0for p, num in self.p.items():if p[0]point[0] or p[1]point[1] or abs(p[0]-point[0]) ! abs(p[1]-point[1]):continuep1 (p[0], point[1])p2 (point[0], p[1])if p1 in self.p and p2 in self.p:ans num*self.p[p1]*self.p[p2] return ans1520 ms 16.7 MB Python3 我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号Michael阿明一起加油、一起学习进步