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);
*/
埋骨何须桑梓地,人生无处不青山
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分: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 最长回文