Leetcode: Line Reflection

时间:2021-07-24 09:52:49
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.

本题精妙之处在于:1. 如何最快找到possible的line的x axis(我最开始想到要用quickselect find median的方法,结果别人有min max方法)

2. 如何最方便确定一个点关于该line的reflection是否存在,由于既有x又有y,不太好处理,别人有个聪明的办法把x跟y组合成string,然后用hashset

学到了:以后处理多个value共同作用的时候,可以考虑wrapper class(但是不好用set), 更应该想一想能不能直接把它们组合成string(直接又好利用set来find)

 public class Solution {
public boolean isReflected(int[][] points) {
int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
HashSet<String> set = new HashSet<>();
for (int[] point : points) {
minX = Math.min(minX, point[0]);
maxX = Math.max(maxX, point[0]);
set.add(point[0] + "a" + point[1]);
}
double sum = minX + maxX;
for (int[] point : points) {
if (!set.contains((int)(sum-point[0]) + "a" + point[1]))
return false;
}
return true;
}
}