给你一个在 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
class DetectSquares:
def __init__(self):
self.map = defaultdict(Counter)
def add(self, point: List[int]) -> None:
x, y = point
self.map[y][x] += 1
def count(self, point: List[int]) -> int:
res = 0
x, y = point
if not y in self.map:
return 0
yCnt = self.map[y]
for col, colCnt in self.map.items():
if col != y:
# 根据对称性,这里可以不用取绝对值
d = col - y
res += colCnt[x] * yCnt[x + d] * colCnt[x + d]
res += colCnt[x] * yCnt[x - d] * colCnt[x - d]
return res
# 作者:LeetCode-Solution
# 链接:https://leetcode-cn.com/problems/detect-squares/solution/jian-ce-zheng-fang-xing-by-leetcode-solu-vwzs/
面试题 01.02. 判定是否互为字符重排
给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
class Solution:
def CheckPermutation(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
s3 = s2 #换个s3 对s2的值的引用
for i in s1:
if i in s3:
s3 = s3.replace(i, '', 1)
else:
return False
return True
# 作者:qaq6666
# 链接:https://leetcode-cn.com/problems/check-permutation-lcci/solution/python-jian-dan-de-dai-ma-jie-jue-fang-a-hxwz/