Skip to content

Latest commit

 

History

History
53 lines (43 loc) · 1.32 KB

File metadata and controls

53 lines (43 loc) · 1.32 KB

223. Rectangle Area

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.

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Note:

Assume that the total area is never beyond the maximum possible value of int.

Solutions (Ruby)

1. Solution

# @param {Integer} a
# @param {Integer} b
# @param {Integer} c
# @param {Integer} d
# @param {Integer} e
# @param {Integer} f
# @param {Integer} g
# @param {Integer} h
# @return {Integer}
def compute_area(a, b, c, d, e, f, g, h)
    area0 = (c - a) * (d - b)
    area1 = (g - e) * (h - f)
    area2 = [[c, g].min - [a, e].max, 0].max * [[d, h].min - [b, f].max, 0].max

    area0 + area1 - area2
end

Solutions (Rust)

1. Solution

impl Solution {
    pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 {
        let area0 = (c - a) * (d - b);
        let area1 = (g - e) * (h - f);
        let area2 = (c.min(g).saturating_sub(a.max(e))).max(0) *
            (d.min(h).saturating_sub(b.max(f))).max(0);

        area0 + area1 - area2
    }
}