当前位置:网站首页>Leetcode-223: rectangular area

Leetcode-223: rectangular area

2022-06-24 10:24:00 Ugly and ugly

Title Description

Here you are The two sides on the surface are composed of straight lines and the edges are parallel to the coordinate axis / Vertical rectangle , Please calculate and return the total area covered by two rectangles .
Each rectangle is represented by its lower left vertex and upper right vertex coordinates :
  The first rectangle consists of its lower left vertex (ax1, ay1) And the top right vertex (ax2, ay2) Definition .
  The second rectangle consists of its lower left vertex (bx1, by1) And the top right vertex (bx2, by2) Definition .

Example

Example 1:
 Insert picture description here 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

The problem solving process

Ideas and steps

(1) General ideas , First calculate the area of two rectangles , Then judge whether it is necessary to subtract the area of the overlapping part according to whether there is overlap ;
(2) If there is overlap , Then you need to calculate the coordinates of the overlapping part .

Code display

public class ComputeArea {
    

    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
    
        int area1 = (ax2 - ax1) * (ay2 - ay1);
        int area2 = (bx2 - bx1) * (by2 - by1);
        if (bx1 >= ax2 || by1 >= ay2 || bx2 <= ax1 || by2 <= ay1) {
    
            //  No overlap 
            return area1 + area2;
        }
        int ax1_ = Math.max(ax1, bx1);
        int ay1_ = Math.max(ay1, by1);
        int ax2_ = Math.min(ax2, bx2);
        int ay2_ = Math.min(ay2, by2);
        int area3 = (ax2_ - ax1_) * (ay2_ - ay1_);
        return area1 + area2 - area3;
    }

    public static void main(String[] args) {
    
        System.out.println(new ComputeArea().computeArea(-3,0,3,4,0,-1,9,2));
    }

}
原网站

版权声明
本文为[Ugly and ugly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240916245159.html