leetcode 850. Rectangle Area II

该博客讨论了LeetCode第850题,题目要求计算一组轴对齐矩形在平面上覆盖的总面积,并给出了解题思路,包括一种巧妙的解法和线段树的解决方案。

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

We are given a list of (axis-aligned) rectangles.  Each rectangle[i] = [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle.

Find the total area covered by all rectangles in the plane.  Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: As illustrated in the picture.

Example 2:

Input: [[0,0,1000000000,1000000000]]
Output: 49
Explanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.

Note:

  • 1 <= rectangles.length <= 200
  • rectanges[i].length = 4
  • 0 <= rectangles[i][j] <= 10^9
  • The total area covered by all rectangles will never exceed 2^63 - 1 and thus will fit in a 64-bit signed integer.

解题思路:

没做出来。。参考leetcode大神的解法,真的很巧妙,对求矩形面积很实用 ;

class Solution {
public:
    int rectangleArea(vector<vector<int>>& rectangles) 
    {
        set<int> ys ;
        long res = 0 , modl = 1000000007 ;
        
        for(auto& rec : rectangles)
        {
            ys.insert(rec[1]) ;
            ys.insert(rec[3]) ;
        }
        
        sort(rectangles.begin() , rectangles.end() , [](auto &a , auto &b){return a[0] < b[0] ;}) ;
        
        int prev_y = *ys.begin() ;
        
        for(auto y : ys)
        {
            long height = y - prev_y ;
            long x_start = rectangles.front()[0] ;
            long x_end = x_start ;
            
            for(auto &rec : rectangles)
            {
                if(rec[1] <= prev_y && rec[3] >= y )
                {
                    if(rec[0] > x_end)
                    {
                        res = (res + (x_end - x_start) * height ) % modl ;
                        x_start = rec[0] ;
                    }
                    if(rec[2] > x_end)
                    {
                        x_end = rec[2] ;
                    }
                }
            }
            
            res = (res + (x_end - x_start) * height ) % modl ;
            prev_y = y ;
        }
        
        return res ;
    }
};

解法二:

还有一种线段树的做法。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值