223.矩形面积
链接:223.矩形面积
难度:Medium
标签:几何、数学
简介:给你 二维 平面上两个 由直线构成的 矩形,请你计算并返回两个矩形覆盖的总面积。
题解 1 - typescript
- 编辑时间:2021-09-30
- 执行用时:140ms
- 内存消耗:44.8MB
- 编程语言:typescript
- 解法介绍:统计 ab 面积和覆盖面积。
function computeArea(
  ax1: number,
  ay1: number,
  ax2: number,
  ay2: number,
  bx1: number,
  by1: number,
  bx2: number,
  by2: number
): number {
  if (bx1 < ax1)
    [ax1, ay1, ax2, ay2, bx1, by1, bx2, by2] = [bx1, by1, bx2, by2, ax1, ay1, ax2, ay2];
  const comp = (x1: number, y1: number, x2: number, y2: number) => (x2 - x1) * (y2 - y1);
  const areaA = comp(ax1, ay1, ax2, ay2);
  const areaB = comp(bx1, by1, bx2, by2);
  if (bx1 > ax2 || by1 > ay2 || by2 < ay1) return areaA + areaB;
  const areaC = comp(
    Math.max(ax1, bx1),
    Math.max(ay1, by1),
    Math.min(ax2, bx2),
    Math.min(ay2, by2)
  );
  return areaA + areaB - areaC;
}