Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Assume that the total area is never beyond the maximum possible value of int.
这道题目,在leetcode上有很多所谓“一句话就实现”的代码。不过我觉得那些代码的可读性太差。下面是我写的代码:
#include<stdio.h> // 计算两条线段重合的部分,如果没有重合的部分,则输出0// 以X轴为示例,先找到两条线段左侧坐标的最大值// 再找到两条线段右侧坐标的最小值// 然后用右侧坐标的最小值减去左侧坐标的最大值// 如果相减得到的值小于0,则表示没有重合// 如果相减得到的值大于等于0,则表示有重合// 相减得到的值即为重合部分的长度 int coverLength(int A, int C, int E, int G){ int maxA = 0; if (A > E){ maxA = A; } else{ maxA = E; } int minC = 0; if (C < G){ minC = C; } else{ minC = G; } int outInt = minC - maxA; if (outInt < 0){ return 0; } return outInt; } int computeRetangleArea(int A, int B, int C, int D){ return (C - A)* (D - B); } // 计算出两个矩形的面积之和,然后再减去重合部分的面积 int computeArea(int A, int B, int C, int D, int E, int F, int G, int H){ int x = coverLength(A, C, E, G); int y = coverLength(B, D, F, H); int coverArea = x*y; int firstArea = computeRetangleArea(A, B, C, D); int lastArea = computeRetangleArea(E, F, G, H); return firstArea + lastArea - coverArea; } void main(){ int area = computeArea(0, 0, 0, 0, -1, -1, 1, 1); printf("%d\n", area); }
时间: 2024-10-08 16:37:01