LeetCode //C - 223. Rectangle Area

223. Rectangle Area

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).
 

Example 1:

在这里插入图片描述

Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45

Example 2:

Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
Output: 16

Constraints:
  • − 1 0 4 < = a x 1 < = a x 2 < = 1 0 4 -10^4 <= ax1 <= ax2 <= 10^4 104<=ax1<=ax2<=104
  • − 1 0 4 < = a y 1 < = a y 2 < = 1 0 4 -10^4 <= ay1 <= ay2 <= 10^4 104<=ay1<=ay2<=104
  • − 1 0 4 < = b x 1 < = b x 2 < = 1 0 4 -10^4 <= bx1 <= bx2 <= 10^4 104<=bx1<=bx2<=104
  • − 1 0 4 < = b y 1 < = b y 2 < = 1 0 4 -10^4 <= by1 <= by2 <= 10^4 104<=by1<=by2<=104

From: LeetCode
Link: 223. Rectangle Area


Solution:

Ideas:
  1. Compute the area of each rectangle individually.
  2. Calculate the overlapping area, if any.
  3. Subtract the overlapping area from the sum of the areas of the two rectangles.
Code:
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
    // Calculate the area of the first rectangle
    int areaA = (ax2 - ax1) * (ay2 - ay1);
    // Calculate the area of the second rectangle
    int areaB = (bx2 - bx1) * (by2 - by1);

    // Find the overlapping area
    int overlapWidth = (ax2 > bx1 && bx2 > ax1) ? (ax2 < bx2 ? ax2 : bx2) - (ax1 > bx1 ? ax1 : bx1) : 0;
    int overlapHeight = (ay2 > by1 && by2 > ay1) ? (ay2 < by2 ? ay2 : by2) - (ay1 > by1 ? ay1 : by1) : 0;
    int overlapArea = overlapWidth * overlapHeight;

    // Total area is the sum of the areas minus the overlapping area
    return areaA + areaB - overlapArea;
}

相关推荐

  1. 2023-12-23周报】

    2024-07-14 09:38:02       53 阅读
  2. 23 easy 226. 翻转二叉树

    2024-07-14 09:38:02       39 阅读
  3. 回顾2023

    2024-07-14 09:38:02       49 阅读
  4. 2023总结

    2024-07-14 09:38:02       53 阅读
  5. Bye~ 2023

    2024-07-14 09:38:02       58 阅读
  6. UVA-213

    2024-07-14 09:38:02       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 09:38:02       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 09:38:02       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 09:38:02       62 阅读
  4. Python语言-面向对象

    2024-07-14 09:38:02       72 阅读

热门阅读

  1. 【AI原理解析】—对抗学习(AL)原理

    2024-07-14 09:38:02       28 阅读
  2. 【nginx】nginx的优点

    2024-07-14 09:38:02       25 阅读
  3. C++多态

    C++多态

    2024-07-14 09:38:02      28 阅读
  4. B树:深入解析与实战应用

    2024-07-14 09:38:02       25 阅读
  5. C语言调用python

    2024-07-14 09:38:02       25 阅读
  6. pytorch GPU cuda 使用 报错 整理

    2024-07-14 09:38:02       26 阅读