2026-01-17-LeetCode刷题笔记-3047-求交集区域内的最大正方形面积

题目信息


题目描述

给定若干轴对齐矩形(用左下角与右上角坐标表示),任选两矩形,取它们的重叠区域。在所有重叠区域中,求能放下的最大正方形面积。


初步思路

  1. 两矩形的交集仍是一个轴对齐矩形,其宽高可由区间交得出。
  2. 交集矩形中最大正方形边长等于 min(交集宽, 交集高),面积为边长平方。
  3. 枚举所有矩形对,更新最大面积即可。

算法分析

  • 核心:枚举矩形对,计算交集宽高并取最小值作为正方形边长
  • 技巧:交集宽高为 min(tx1, tx2) - max(bx1, bx2) 与 min(ty1, ty2) - max(by1, by2)
  • 正确性简述:任意两矩形的交集范围唯一,交集内能放下的最大正方形边长由更短边决定,枚举所有矩形对即可覆盖全局最优
  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)

代码实现(C++)

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    long long largestSquareArea(vector<vector<int>>& bottomLeft,
                                vector<vector<int>>& topRight) {
        long long max_side = 0;
        int n = (int)bottomLeft.size();
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                int bx1 = bottomLeft[i][0], by1 = bottomLeft[i][1];
                int tx1 = topRight[i][0], ty1 = topRight[i][1];
                int bx2 = bottomLeft[j][0], by2 = bottomLeft[j][1];
                int tx2 = topRight[j][0], ty2 = topRight[j][1];

                int width = min(tx1, tx2) - max(bx1, bx2);
                int height = min(ty1, ty2) - max(by1, by2);
                int side = min(width, height);
                if (side > 0) max_side = max(max_side, (long long)side);
            }
        }
        return max_side * max_side;
    }
};

测试用例

输入 输出 说明
bottomLeft = \[1,1,2,2], topRight = \[3,3,4,4] 1 交集为 1x1,最大正方形面积 1
bottomLeft = \[0,0,1,0], topRight = \[2,1,3,2] 0 交集高度为 0,无法放正方形
bottomLeft = \[0,0,2,1,3,3], topRight = \[3,3,4,4,5,5] 1 取最优矩形对得到边长 1

总结与反思

  1. 交集矩形的最大正方形边长由短边决定,先算交集再取最小值即可。
  2. 枚举矩形对即可覆盖全局最优,注意 side > 0 才是有效交集。
相关推荐
geats人山人海11 小时前
算法基础第六讲 图论
算法·深度优先·图论
Rain的Java大神之路13 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
风落青芜14 小时前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法
@陈小鱼15 小时前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
ZYH_060119 小时前
Shell 第一阶段笔记:变量、引号与变量截取
前端·chrome·笔记
星恒随风20 小时前
从0实现C++ AI大模型接入SDK(七):Ollama本地模型部署、NDJSON流式响应与LLMManager模型管理
linux·开发语言·c++·人工智能·笔记
liulilittle21 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
琳少_21 小时前
java课堂笔记
java·开发语言·数据库·笔记
3095566661 天前
股票接口日期参数为什么不起作用:五组请求对照与逐字节比对排查笔记
服务器·数据库·笔记·python·量化·api接口·股票接口