边工作边刷题:70天一遍leetcode: day 96-1
Line Reflection
要点:
- 一个confusion:找到所有点的median为什么不行?重复的点的情况,另外unsorted找median没有max/min中点容易
- 注意y轴对称要验证x
- 公式:2*x-x0:x-x0就是对称边的delta,所以再加个x就是所求
- 这题还要考虑y坐标相等:一个x可以有多个y点对应,所以要用adjList的结构
错误点:
- 取某一维向量应该用list comprehension,而不是用zip:zip只是对n个list,产生一个tuple的list
- 因为中点不一定int,要用float来取mid point
from collections import defaultdict
class Solution(object):
def isReflected(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
if not points: return True
xs = [p[0] for p in points]
maxx, minx = max(xs), min(xs)
x = (maxx + minx)/2.0 # error 1: float
umap = defaultdict(list)
for p in points:
umap[p[0]].append(p[1])
for p in points:
if (2*x-p[0] not in umap) or (p[1] not in umap[2*x-p[0]]):
return False
return True
s = Solution()
assert not s.isReflected([[1,1],[-1,-1]]), "False"
assert s.isReflected([[0,0],[1,0]]), "True"