码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode之Rectangle Area

时间:2015-06-09 00:42:47      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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.

技术分享

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

 

这道题目,在leetcode上有很多所谓“一句话就实现”的代码。不过我觉得那些代码的可读性太差。下面是我写的代码:

#include<stdio.h>

// 计算两条线段重合的部分,如果没有重合的部分,则输出0
// 以X轴为示例,先找到两条线段左侧坐标的最大值
// 再找到两条线段右侧坐标的最小值
// 然后用右侧坐标的最小值减去左侧坐标的最大值
// 如果相减得到的值小于0,则表示没有重合
// 如果相减得到的值大于等于0,则表示有重合
// 相减得到的值即为重合部分的长度 int coverLength(int A, int C, int E, int G){ int maxA = 0; if (A > E){ maxA = A; } else{ maxA = E; } int minC = 0; if (C < G){ minC = C; } else{ minC = G; } int outInt = minC - maxA; if (outInt < 0){ return 0; } return outInt; } int computeRetangleArea(int A, int B, int C, int D){ return (C - A)* (D - B); }
// 计算出两个矩形的面积之和,然后再减去重合部分的面积
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H){ int x = coverLength(A, C, E, G); int y = coverLength(B, D, F, H); int coverArea = x*y; int firstArea = computeRetangleArea(A, B, C, D); int lastArea = computeRetangleArea(E, F, G, H); return firstArea + lastArea - coverArea; } void main(){ int area = computeArea(0, 0, 0, 0, -1, -1, 1, 1); printf("%d\n", area); }

 

leetcode之Rectangle Area

标签:

原文地址:http://www.cnblogs.com/liu-binq63/p/4562231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!