LeetCode 2013. 检测正方形

2013. 检测正方形

Solution

思路:和我的思路大概一致,我想的是枚举同一行,题解是枚举同一列,因为确定一个点,长度有了,其他的点也就确定。因此枚举查询点同一列的点,然后距离有了,就在这两个高度的行中找对应的点是否存在。

class DetectSquares {
    Map<Integer, Map<Integer, Integer>> cnt;
    public DetectSquares() {
        cnt = new HashMap<Integer, Map<Integer, Integer>>();
    }
    
    public void add(int[] point) {
        int x = point[0], y = point[1];
        cnt.putIfAbsent(y, new HashMap<Integer, Integer>());
        Map<Integer, Integer> yCnt = cnt.get(y);
        yCnt.put(x, yCnt.getOrDefault(x, 0) + 1);
    }
    
    public int count(int[] point) {
        int res = 0;
        int x = point[0], y = point[1];
        if (!cnt.containsKey(y)) {
            return 0;
        }
        Map<Integer, Integer> yCnt = cnt.get(y);
        Set<Map.Entry<Integer, Map<Integer, Integer>>> entries = cnt.entrySet();
        for (Map.Entry<Integer, Map<Integer, Integer>> entry : entries) {
            int col = entry.getKey();
            Map<Integer, Integer> colCnt = cnt.get(col);
            if (col != y) {
                int d = y - col;
                res += colCnt.getOrDefault(x, 0) * yCnt.getOrDefault(x + d, 0) * colCnt.getOrDefault(x + d, 0);
                res += colCnt.getOrDefault(x, 0) * yCnt.getOrDefault(x - d, 0) * colCnt.getOrDefault(x - d, 0);
            }
        }
        return res;
    }
}

/**
 * Your DetectSquares object will be instantiated and called as such:
 * DetectSquares obj = new DetectSquares();
 * obj.add(point);
 * int param_2 = obj.count(point);
 */
posted @   Frontierone  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2019-01-27 kuangbin专题十六 KMP&&扩展KMP HDU3294 Girls' research
2019-01-27 kuangbin专题十六 KMP&&扩展KMP HDU3068 最长回文
点击右上角即可分享
微信分享提示