算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 矩形面积,我们先来看题面:
https://leetcode-cn.com/problems/count-complete-tree-nodes/
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
在二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。
示例
解题
对于同一水平线上的两条线段 [a, b] 和 [c, d] ,它们的交集为 [max(a, c), min(b, d)]。
我们分别求出横轴和纵轴上的交集,判断是否相交,如果不相交,则面积为两个矩形面积之和,否则减去相交部分面积。
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
long area = (long)(C - A) * (D - B) + (long)(G - E) * (H - F);
long dx = min( C, G ) + 0LL - max( A, E );
if ( dx < 0 ) return area;
long dy = min( D, H ) + 0LL - max( B, F );
if ( dy < 0 ) return area;
return area - dx * dy;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: