美文网首页
Lintcode454 Rectangle Area solut

Lintcode454 Rectangle Area solut

作者: 程风破浪会有时 | 来源:发表于2018-03-14 08:26 被阅读0次

【题目描述】

Implement a Rectangle class which include the following attributes and methods:

Two public attributes width and height.

A constructor which expects two parameters width and height of type int.

A method getArea which would calculate the size of the rectangle and return.

实现一个矩阵类Rectangle,包含如下的一些成员变量与函数:

两个共有的成员变量 width 和 height 分别代表宽度和高度。

一个构造函数,接受2个参数 width 和 height 来设定矩阵的宽度和高度。

一个成员函数 getArea,返回这个矩阵的面积。

【题目链接】

www.lintcode.com/en/problem/rectangle-area/

【题目解析】

这道题最关键的是要找出重叠的部分,两个矩形的面积和-重叠部分的面积就是答案。

观察重叠部分,肯定都是在中间,需要找出重叠部分上下左右的边。重叠部分左边界肯定是两个矩形左边界的较大者,同理,重叠部分右边界肯定是两个矩形右边界的较小者。这里可以用一个小技巧,即取右边界时,和刚才取的左边界比较,取两者中的较大者为右边界,这样就把两个矩形没有重叠的情况也包括进来了(没有重叠的话在这里重叠部分的左右边界会相同,也就是宽为0,面积自然就是0),不用单独讨论了。以此类推,可以求出重叠部分的上下边界。

【参考答案】

www.jiuzhang.com/solutions/rectangle-area/

相关文章

网友评论

      本文标题:Lintcode454 Rectangle Area solut

      本文链接:https://www.haomeiwen.com/subject/szmkoxtx.html