• 5877. 检测正方形 力扣周赛(中等 ) 题意读错,写复杂


    5877. 检测正方形

    给你一个在 X-Y 平面上的点构成的数据流。设计一个满足下述要求的算法:

    添加 一个在数据流中的新点到某个数据结构中。可以添加 重复 的点,并会视作不同的点进行处理。
    给你一个查询点,请你从数据结构中选出三个点,使这三个点和查询点一同构成一个 面积为正 的 轴对齐正方形 ,统计 满足该要求的方案数目。
    轴对齐正方形 是一个正方形,除四条边长度相同外,还满足每条边都与 x-轴 或 y-轴 平行或垂直。

    实现 DetectSquares 类:

    DetectSquares() 使用空数据结构初始化对象
    void add(int[] point) 向数据结构添加一个新的点 point = [x, y]
    int count(int[] point) 统计按上述方式与点 point = [x, y] 共同构造 轴对齐正方形 的方案数。

    示例:

    代码:

    开始题目理解错了,以为是矩形,其实是正方形,

    自己写的代码有点复杂,枚举对角点。。

    其实:map<pair<int,int>,int>  mp;  效果等价  map<int, map<int, int>> mp; 

    class DetectSquares {
    public:
       
        map<pair<int,int>,int> mp;
        
        DetectSquares() {
    
        }
        
        void add(vector<int> point) {
    
          mp[make_pair(point[0],point[1])]++;
          return;
        }
        
        int count(vector<int> point) {
         int cnt=0;
         for(auto i:mp)
         {
             pair<int,int> p=i.first;
             if(p.first==point[0] || p.second==point[1]) continue;
             if(abs(p.first-point[0])!=abs(p.second-point[1])) continue;
             cnt+=mp[p]*mp[make_pair(p.first,point[1])]*mp[make_pair(point[0],p.second)];
         }
            return cnt;
        }
    };
    
    /**
     * Your DetectSquares object will be instantiated and called as such:
     * DetectSquares* obj = new DetectSquares();
     * obj->add(point);
     * int param_2 = obj->count(point);
     */

    简单写法:

    class DetectSquares {
    public:
        map<int, map<int, int>> mp;
        DetectSquares() {
        }
        
        void add(vector<int> point) {
            mp[point[0]][point[1]] += 1;
        }
        
        int get(int x, int y) {
            if (not mp.count(x)) return 0;
            if (not mp[x].count(y)) return 0;
            return mp[x][y];
        }
        
        int count(vector<int> point) {
            int x = point[0], y = point[1];
            int ans = 0;
            for (auto [y1, c] : mp[x]) {
                if (y1 != y) {
                    ans += c * get(x + abs(y1 - y), y1) * get(x + abs(y1 - y), y);
                    ans += c * get(x - abs(y1 - y), y1) * get(x - abs(y1 - y), y);
                }
            }
            return ans;
        }
    };
    
    /**
     * Your DetectSquares object will be instantiated and called as such:
     * DetectSquares* obj = new DetectSquares();
     * obj->add(point);
     * int param_2 = obj->count(point);
     */
  • 相关阅读:
    监控网速
    nginx与apache 对比 apache是同步多进程模型,一个连接对应一个进程;nginx是异步的,多个连接(万级别)可以对应一个进程
    shell 爬虫
    shell 读写远程数据库
    tmp
    交换分区 在dd命令执行期间 top 其消耗系统约14%的cpu,而mem占比约为0
    中间变量 加层 对解决问题的思路 逆序生成
    ALLOWED_HOSTS = ['*']
    搭建一个简单的Python的Web环境 监控服务器内存 线程 进程 网络
    小米加步枪
  • 原文地址:https://www.cnblogs.com/stepping/p/15314226.html
Copyright © 2020-2023  润新知