leetcode-2013:检测正方形

简介: leetcode-2013:检测正方形

题目

题目链接

给你一个在 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 。你可以选择:
                               //   - 第一个,第二个,和第三个点
                               //   - 第一个,第三个,和第四个点

解题

方法一:哈希表

参考链接

class DetectSquares {
public:
    unordered_map<int,unordered_map<int,int>> cnt;
    DetectSquares() {
    }
    void add(vector<int> point) {
        int x=point[0],y=point[1];
        cnt[y][x]++;
    }
    int count(vector<int> point) {
        int res=0;
        int x=point[0],y=point[1];
        if(!cnt.count(y)){
            return 0;
        }
        unordered_map<int,int> yCnt=cnt[y];
        for(auto&[col,colCnt]:cnt){
            if(col!=y){
                int d=col-y;// 根据对称性,这里可以不用取绝对值(后续用到+d和-d)
                res+=colCnt[x]*colCnt[x+d]*yCnt[x+d];
                res+=colCnt[x]*colCnt[x-d]*yCnt[x-d];
                // res += (colCnt.count(x) ? colCnt[x] : 0) * (yCnt.count(x + d) ? yCnt[x + d] : 0) * 
                //        (colCnt.count(x + d)? colCnt[x + d] : 0);
                // res += (colCnt.count(x) ? colCnt[x] : 0) * (yCnt.count(x - d) ? yCnt[x - d] : 0) * 
                //        (colCnt.count(x - d) ? colCnt[x - d] : 0);
            }
        }
        return res;
    }
};

注意:使用colCnt.count(x) ? colCnt[x] : 0 速度比 colCnt[x]


相关文章
|
6天前
|
存储
leetcode2975. 移除栅栏得到的正方形田地的最大面积
leetcode2975. 移除栅栏得到的正方形田地的最大面积
22 1
|
6天前
|
算法 程序员 索引
【Leetcode 程序员面试金典 02.08】 —— 环路检测 |双指针
我们可以使用双指针解决本题,由数学推导可知:a 的距离为(环长度的倍数 - b),即 tmp 指针从头节点走到环开头节点等于 slow 指针走到环开头节点的距离
|
6天前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 221. 最大正方形 算法解析
☆打卡算法☆LeetCode 221. 最大正方形 算法解析
|
6天前
leetcode:520. 检测大写字母
leetcode:520. 检测大写字母
16 0
|
6天前
leetcode-221:最大正方形
leetcode-221:最大正方形
30 0
|
6天前
leetcode-593:有效的正方形
leetcode-593:有效的正方形
19 0
|
6天前
|
Go
golang力扣leetcode 221.最大正方形
golang力扣leetcode 221.最大正方形
22 0
LeetCode-593 有效的正方形
LeetCode-593 有效的正方形
|
6天前
leetcode-1725:可以形成最大正方形的矩形数目
leetcode-1725:可以形成最大正方形的矩形数目
18 0
|
6天前
|
Go
golang力扣leetcode 2013.检测正方形
golang力扣leetcode 2013.检测正方形
22 0