python刷题-检测正方形(哈希表法)+collections模块+sorted()

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、个人题解

# 报错/超出时间限制  没发现原因 但以后注意不要写这种重复的循环

思想:第一层循环遍历跟目标点相同X轴的点,找到边长,此时这个正方形已经是已知的了(边长加两个点),在此基础上进入第二层循环找到与目标点相同Y轴的点且满足边长相同。确定两个点后,通过第三层循环寻找最后一个点,最后一个点的横纵坐标分别是前两个点的横纵坐标,遍历找到它。

class DetectSquares:
    def __init__(self):
        self.pointset = []

    def add(self, point: list[int]) -> None:
        self.pointset.append(point)

    def count(self, point: list[int]) -> int:
        count = 0
        a = self.pointset
        x, y = point
        for i in a:
            if i[0] == x and abs(y - i[1] != 0):
                l = abs(y - i[1])
                for j in a:
                    if j[1] == y and abs(x - j[0]) == l:
                        for k in a:
                            if k == [j[0], i[1]]:
                                count += 1
        return count

3、官方题解

https://leetcode-cn.com/problems/detect-squares/solution/jian-ce-zheng-fang-xing-by-leetcode-solu-vwzs/

from collections import defaultdict, Counter
class DetectSquares:

    def __init__(self):
        self.map = defaultdict(Counter)  # 嵌套哈希表(字典)

    def add(self, point):
        x, y = point
        self.map[y][x] += 1

    def count(self, point):
        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


# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)

没啥好说的,哈希表面对这种已经有(或者说方便去遍历)全部的数据流而去寻找目标点的问题就是Yyds

4. from collections import defaultdict, Counter

4个非常有用的python内置数据结构(array, defaultdict, named tuple, counter)_yanxiangtianji的专栏-CSDN博客https://blog.csdn.net/yanxiangtianji/article/details/116215484defaultdict()定义一个字典,其中value都是预设值

counter()同时对输入进行计数,返回一个字典。

c = Counter('gallahad')                 # a new counter from an iterable
print(c)
# Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})

官方文档中这个用法

self.map = defaultdict(Counter)  # 嵌套哈希表(字典)

self.map[y][x] += 1

self.map[y]是外层字典,而self.map[y][x]是内层字典(counter)

如果说用直接初始化字典构造嵌套字典,需要如下的类似操作

d = dict()
d["a"] = {}
d["a"]["b"] = 1

5.sorted()函数

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

python的sorted函数_啥也不是-CSDN博客_sorted函数python一、sort函数如果对python中的列表进行排序,可以使用List类的成员函数sort,该函数会在原空间上进行操作,对列表本身进行修改,不返回副本。语法如下:L.sort(cmp=None, key=None, reverse=False)二、sorted函数sorted函数就比sort函数要强大许多了,sort只能对列表进行排序,sorted可以对所有可迭代类型进行排序,并且返回新的...https://blog.csdn.net/bcfdsagbfcisbg/article/details/82801835

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值