LeetCode 2013. 检测正方形(字典)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 2013. 检测正方形(字典)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 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] 共同構造 軸對齊正方形 的方案數。
示例:
來源:力扣(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 改進
- 枚舉對角線的另一點
1520 ms 16.7 MB Python3
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 2013. 检测正方形(字典)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode meituan-001
- 下一篇: LeetCode 1933. 判断字符串