356. Line Reflection
Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points.
Example 1:
Given points = [[1,1],[-1,1]]
, return true
.
Example 2:
Given points = [[1,1],[-1,-1]]
, return false
.
Follow up:
Could you do better than O($n^2$)?
Hint:
- Find the smallest and largest x-value for all points.
- If there is a line then it should be at y = (minX + maxX) / 2.
- For each point, make sure that it has a reflected point in the opposite side.
题意是给出很多点,看有没有一个平行于y轴的线让所有的点关于这个线对称。在坐标轴上这个线其实就是 x = a
,a可以为任意数.
- 提示给的很好,先找出所有点(x, y)中x的最大值maxX和最小值minX
- 如果有一个对称线,那这个线一定是
x = (maxX + minX) / 2
。 提示给的是y = ?
,不够严谨,是错误的。 - 如何找一个点的对称点?如果(x1, y1), (x2, y2),关于
x = a
对称,说明y1 = y2
,(x1 + x2) / 2 = a
. 因为a = (maxX + minX) / 2
, 所以x2 = maxX + minX - x1
. - 先遍历一所有点,把所有点放到HashSet里。然后在遍历一遍所有点,求出相应的对称点。如果对称点不在HashSet里,说明找不到对称轴。
代码如下: