题目描述:
题解一:未通过
思路:
1.根据输入的rectangle确定一个范围area,area是一个矩形,左下右上坐标分别为:
left = min(rectangles[i][0] for i in range(len(rectangles))) bottom = min(rectangles[i][1] for i in range(len(rectangles))) right = max(rectangles[i][2] for i in range(len(rectangles))) top = max(rectangles[i][3] for i in range(len(rectangles)))
如果最终所有的rectangle恰好围成一个矩形,这个矩形就是area。
2.area中所有坐标值都初始化为0,依次将rectangle中的每个矩形在area中对应的位置的坐标值加1(如果最终[i,j]未被覆盖,则area[i,j]=0,如果[i,j]被多次覆盖,则area[i,j]>1)
3.如果最后area范围中所有值为1的坐标数量和area对应区域的面积相等,则返回true,否则false。
class Solution(object): def isRectangleCover(self, rectangles): left = min(rectangles[i][0] for i in range(len(rectangles))) bottom = min(rectangles[i][1] for i in range(len(rectangles))) right = max(rectangles[i][2] for i in range(len(rectangles))) top = max(rectangles[i][3] for i in range(len(rectangles))) rec_length = top-bottom rec_width = right-left area = [[0 for i in range(rec_width)]for j in range(rec_length)] for rec in rectangles: rec_left = rec[0] rec_bottom = rec[1] rec_right = rec[2] rec_top = rec[3] for i in range(rec_left,rec_right): for j in range(rec_bottom,rec_top): area[j-bottom][i-left]=area[j-bottom][i-left]+1 totol = rec_width*rec_length size = 0 for i in range(len(area)): for j in range(len(area[0])): if area[i][j]==1: size=size+1 if size==totol: return True return False
最终前面的用例都可以通过,但在第42/47个用例超时。
题解二:参考391. 完美矩形(Python) - 简书
如果要构成完美矩形,需要满足:
1.rectangle的所有上下左右四个顶点中,除了最终构成的完美矩形的四个顶点出现奇数次,其他全部出现次数为偶数。
2.完美矩形的最终面积小于各个小矩形面积之和。
利用set保存坐标,定义一个pos_set_handel函数,如果pos已经在set中存在则将其remove,否则将其加入set,判断最终set中是否只有4个元素。
class Solution(object): def isRectangleCover(self, rectangles): max_val = sys.maxsize min_val = -sys.maxsize-1 bound = [max_val,max_val,min_val,min_val] sum_rectangles_areas = 0 pos_set = set() for x1,y1,x2,y2 in rectangles: bound[0] = min(bound[0], x1, x2) bound[1] = min(bound[1], y1, y2) bound[2] = max(bound[2], x1, x2) bound[3] = max(bound[3], y1, y2) sum_rectangles_areas = sum_rectangles_areas+(x2-x1)*(y2-y1) self.pos_set_handle((x1,y1),pos_set) self.pos_set_handle((x1, y2), pos_set) self.pos_set_handle((x2, y1), pos_set) self.pos_set_handle((x2, y2), pos_set) if len(pos_set)!=4: return False elif (bound[0],bound[1]) in pos_set and (bound[0],bound[3]) in pos_set and (bound[2], bound[1]) in pos_set and (bound[2],bound[3]) in pos_set and sum_rectangles_areas == (bound[2] - bound[0]) * (bound[3] - bound[1]): return True return False def pos_set_handle(self,pos,pos_set): if pos in pos_set: pos_set.remove(pos) else: pos_set.add(pos)