from typing import List
from collections import Counter
class Solution:
def isRectangleCover(self, rectangles) -> bool:
rects = [Rectangle(*item) for item in rectangles]
counter = Counter()
for rect in rects:
counter.update(rect.getFourPoints())
r = []
for k,v in counter.items():
if v%2!=0 and v!=1:
return False
elif v==1:
r.append(k)
if len(r)>4:
return False
if len(r)!=4:
return False
xs = [i[0] for i in r]
ys = [i[1] for i in r]
w = max(xs)-min(xs)
h = max(ys)-min(ys)
return sum([rect.getArea() for rect in rects])==w*h
class Rectangle:
def __init__(self,x,y,x2,y2):
self.x = x
self.y = y
self.x2 = x2
self.y2 = y2
self.w = x2-x
self.h = y2-y
def getArea(self):
return self.w*self.h
def getFourPoints(self):
a = (self.x,self.y)
b = (self.x,self.y2)
c = (self.x2,self.y)
d = (self.x2,self.y2)
return [a,b,c,d]
这道题对于重叠的判断好难想啊,我是看了题解才知道怎么做。在做题过程中,又学会了一些东西,记载如下
1 python3里面的list.sort函数没有cmp参数了,只有key参数,所以需要借助functools里面的cmp_to_key来把cmp函数转换为key函数。知乎上有关于这方面的讨论,可以看看。
2 python2里面的cmp函数是a>b,返回1(或者正数),a<b,返回-1(或者负数),a=b,返回0.但是c++的stl里面,cmp是返回a<b
3 怎样判断两个矩形是否有交集?
矩形a (x1,y1) (x2,y2)
矩形b (x3,y3) (x4,y4)
则 max(x1,x3)<min(x2,x4)&&max(y1,y3)<min(y2,y4)
这个逻辑表达式就可以判断两矩形是否有重叠部分。
原文:https://www.cnblogs.com/digdig/p/13233363.html