博客
关于我
【Leetcode】223. Rectangle Area
阅读量:194 次
发布时间:2019-02-28

本文共 1179 字,大约阅读时间需要 3 分钟。

给定平面直角坐标系中两个矩形,求其边界围成的区域的面积。计算两个矩形重叠部分即可,如果没有重叠则直接返回两个矩形面积之和,否则返回面积之和减去重叠部分的面积。

代码解析:

public class Solution {    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        // 计算重叠部分的左、右边界坐标        int left = Math.max(A, E);        int right = Math.min(C, G);        // 计算重叠部分的上、下边界坐标        int low = Math.max(B, F);        int up = Math.min(D, H);        // 计算两个矩形的面积之和        int sum = (C - A) * (D - B) + (G - E) * (H - F);        // 判断是否有重叠        if (right <= left || up <= low) {            return sum; // 没有重叠时,直接返回面积之和        }        // 计算重叠部分的面积        int overlap = (right - left) * (up - low);        return sum - overlap; // 有重叠时,返回面积之和减去重叠部分    }}

代码解释:

  • 确定重叠边界:

    • left = Math.max(A, E):取两个矩形左边界较大的一个。
    • right = Math.min(C, G):取两个矩形右边界较小的一个。
    • low = Math.max(B, F):取两个矩形下边界较大的一个。
    • up = Math.min(D, H):取两个矩形上边界较小的一个。
  • 计算面积之和:

    • 第一个矩形面积:(C - A) * (D - B)
    • 第二个矩形面积:(G - E) * (H - F)
    • 总面积:sum = (C - A) * (D - B) + (G - E) * (H - F)
  • 判断是否有重叠:

    • 如果 right <= leftup <= low,说明没有重叠,直接返回总面积。
  • 计算并返回重叠部分面积:

    • 重叠宽度:right - left
    • 重叠高度:up - low
    • 重叠面积:overlap = (right - left) * (up - low)
    • 最终返回总面积减去重叠面积。
  • 时空复杂度:

    该算法的时间复杂度为 O(1),因为所有操作仅涉及基本的算术运算和条件判断,无需循环或其他复杂操作。

    转载地址:http://azcs.baihongyu.com/

    你可能感兴趣的文章
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>