其他分享
首页 > 其他分享> > 每日n刷:leetcode 2013. 检测正方形

每日n刷:leetcode 2013. 检测正方形

作者:互联网

2013. 检测正方形

https://fishi.top/fishpic/caa3553f-6eeb-4db9-8174-ead8f7ad620b.png

https://fishi.top/fishpic/be72f14d-d45c-48ac-a1dc-938fe66f2a26.png

枚举

枚举

这题找的是正方形!一定要好好审题!不过已经做下去了就黑着脸做完吧!

我当时做的时候先找到了矩形,提交用例不过debug才发现原来只要正方形,那么直接根据target对应的那个点的x,y值判断是否一样就可以,注意一下,需要取绝对值!!!

class DetectSquares {

    // 坐标图 存储坐标对应的点数
    int[][] map;
    public DetectSquares() {
        this.map = new int[1010][1010];
    }
    
    public void add(int[] point) {
        this.map[point[0]][point[1]] ++;
    }
    
    public int count(int[] point) {
        List<Integer> x = new ArrayList<>();
        List<Integer> y = new ArrayList<>();
        for(int i = 0; i < map.length; i ++) {
            // 取同列存在的点坐标
            if(map[point[0]][i] > 0 && i != point[1]) {
                y.add(i);
            }
            // 取同行存在的点坐标
            if(map[i][point[1]] > 0 && i != point[0]) {
                x.add(i);
            }
        }
        int cnt = 0;
        for(int i = 0; i < x.size(); i ++) {
            for(int j = 0; j < y.size(); j ++) {
                // 看三点对应的另一个点的矩形是否存在,如果存在看长度是否能组成正方形
                if(map[x.get(i)][y.get(j)] > 0 && Math.abs(x.get(i) - point[0]) == Math.abs(y.get(j) - point[1])) {
                    // 取同一坐标不同点的笛卡尔集之和
                    int tmp = map[x.get(i)][point[1]] * map[x.get(i)][y.get(j)] * map[point[0]][y.get(j)];
                    cnt += tmp;
                }
            }
        }
        return cnt;
    }
}

标签:map,point,int,get,++,正方形,leetcode,2013
来源: https://blog.csdn.net/AlexanderRon/article/details/122701897