Line Reflection

来源:互联网 发布:python 迭代器 生成器 编辑:程序博客网 时间:2024/04/29 22:29

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:

  1. Find the smallest and largest x-value for all points.
  2. If there is a line then it should be at y = (minX + maxX) / 2.
  3. For each point, make sure that it has a reflected point in the opposite side.

Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.

思路:这题提示已经给的很明显了,不过要注意的地方就是hashmap的定义,key是x,value应该是个set,刚开始我犯了个错误,定义成了Node,这样会覆盖点,因为x 相同的点有很多,而他们y不相同,所有后面要用个set来保存所有x相同的点的y坐标。这点我调试了半天才弄明白。然后算就是计算中线的x值,也就是最小值和最大值的和除以2.然后注意先转换成double然后要转换成int来算,因为原来给的坐标都是int值。

public class Solution {    public boolean isReflected(int[][] points) {        if(points == null ) return false;        int minX = Integer.MAX_VALUE;        int maxX = Integer.MIN_VALUE;        HashMap<Integer, Set<Integer>> hashmap = new HashMap<Integer, Set<Integer>>();        for(int i=0; i<points.length; i++){            minX = Math.min(minX, points[i][0]);            maxX = Math.max(maxX, points[i][0]);            if(hashmap.containsKey(points[i][0])){                hashmap.get(points[i][0]).add(points[i][1]);            } else {                Set<Integer> hashset = new HashSet<Integer>();                hashset.add(points[i][1]);                hashmap.put(points[i][0], hashset);            }        }                double mid = (minX + maxX)/2.0;        for(int i=0; i<points.length; i++){            int key = (int)(2*mid-points[i][0]);            if(!hashmap.containsKey(key) || !hashmap.get(key).contains(points[i][1])){                return false;            }        }        return true;    }}


0 0
原创粉丝点击