Question:
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(n2)?
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.
Explanation:
刚开始的思路是, 用一个map存{y值:[所有相应x值]}。 对于每一个y值,将其对应的x值的list排序。用two pointers检查是不是对称。 这样的复杂度超过O(n^2)了,sort就已经O(nlogn)了。 于是,按照了hint写,先遍历一遍,得到x最大值和最小值,从而得到x中间值。再遍历一遍,存下每个点的对称点。最后遍历一遍,如果有哪个坐标不在set里面,说明没有对称点。(和two sum一样的思路)