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(n2)?
public class Solution {
public boolean isReflected(int[][] points) {
if(points == null || points.length <=1 ) return true;
int left =points[0][0];
int right = left;
Map<Integer, Set<Integer>> map = new HashMap<>();
for(int[] p : points){
left = Math.min(p[0], left);
right = Math.max(p[0], right);
if(!map.containsKey(p[1])){
Set<Integer> set = new HashSet<>();
set.add(p[0]);
map.put(p[1], set);
}else{
map.get(p[1]).add(p[0]);
}
}
for(int[] p : points){
Set<Integer> s = map.get(p[1]);
if(!s.contains(left + right - p[0])) return false;
}
return true;
}
}