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)?
本题目要求求一个平行于y轴的直线,看points是否对于y轴对称。实现起来比较简单,对称的线肯定是最大和最小点正中间的线,推理如下代码如下:
1 public class Solution { 2 public boolean isReflected(int[][] points) { 3 int min = Integer.MAX_VALUE; 4 int max = Integer.MIN_VALUE; 5 Set<String> set = new HashSet<String>(); 6 for(int[] p:points){ 7 min = Math.min(p[0],min); 8 max = Math.max(p[0],max); 9 String str = p[0]+"a"+p[1]; 10 set.add(str); 11 } 12 int sum = min+max; 13 for(int[] p:points){ 14 String str = (sum-p[0]+"a"+p[1]); 15 if(!set.contains(str)) return false; 16 } 17 return true; 18 } 19 }