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)?
一刷
題解:一種很簡單的思路。先找到那個反射面。所以我們要先找到所有點中x最小的申窘,x最大的敞临,它們的平均值即是反射面sum/2。然后再將所有點p[0] + "a" + p[1]存入set中,如果sum - p[0] + "a" + p[1]不在set中。return false
class Solution {
public boolean isReflected(int[][] points) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
HashSet<String> set = new HashSet<>();
for(int[] p : points){
max = Math.max(max, p[0]);
min = Math.min(min, p[0]);
String str = p[0] + "a" + p[1];
set.add(str);
}
int sum = max + min;
for(int[] p:points){
String str = (sum-p[0]) + "a" + p[1];
if( !set.contains(str)) return false;
}
return true;
}
}