因为考虑到重合的情况,所以就要计算重叠部分的面积。
采用投影计算重叠的长和宽。
即把平行的边分别投影到x轴和y轴上,重合部分的长即为Math.min(ax2,bx2) - Math.max(ax1,bx1);
宽同理。即可在o(1)时间内得到结果。
var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) {
let res = (ax2 - ax1)*(ay2 - ay1) + (bx2 - bx1)*(by2 - by1);
let width = Math.min(ay2,by2) - Math.max(ay1,by1);
let len = Math.min(ax2,bx2) - Math.max(ax1,bx1);
res -= Math.max(width,0)*Math.max(len,0);
return res;
};