Leetcode 3047. Find the Largest Area of Square Inside Two Rectangles

本文介绍了LeetCode问题3047的解题思路,采用暴力搜索算法,通过二重循环计算两个矩形交叉部分中可能的最大正方形面积。给出了Python代码实现,并分析了其时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 解题思路

这道题倒是没啥特别的思路,直接暴力求解就是了,因此就是一个 O ( N 2 ) O(N^2) O(N2)的二重循环遍历任意两个矩形交叉部分当中可能的最大的正方形的面积。

然后,关于交叉部分的最大正方形的面积,这里又是一个分类讨论的问题,我们需要讨论以下两个矩形的分布情况,然后给出最终的答案。

2. 代码实现

给出python代码实现如下:

class Solution:
    def largestSquareArea(self, bottomLeft: List[List[int]], topRight: List[List[int]]) -> int:
        ans = 0
        n = len(bottomLeft)
        
        def get_intersection(rec1, rec2):
            if rec1[0] > rec2[0]:
                return get_intersection(rec2, rec1)
            if rec1[2] <= rec2[0]:
                return 0
            elif rec1[1] >= rec2[3] or rec1[3] <= rec2[1]:
                return 0
            l = min(rec2[2], rec1[2]) - rec2[0]
            if rec1[1] <= rec2[1]:
                h = min(rec1[3], rec2[3]) - rec2[1]
            else:
                h = min(rec1[3], rec2[3]) - rec1[1]
            d = min(h, l)
            return d * d
        
        for i in range(n):
            rec1 = [bottomLeft[i][0], bottomLeft[i][1], topRight[i][0], topRight[i][1]]
            for j in range(i+1, n):
                rec2 = [bottomLeft[j][0], bottomLeft[j][1], topRight[j][0], topRight[j][1]]
                ans = max(ans, get_intersection(rec1, rec2))
        return ans

提交代码评测得到:耗时4690ms,占用内存17.4MB。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值