356. Line Reflection
来源:互联网 发布:淘宝骑行头盔 编辑:程序博客网 时间:2024/05/16 11:45
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.
Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.
public class Solution { private class Point { int x; int y; public Point(int px, int py) { this.x = px; this.y = py; } } public boolean isReflected(int[][] points) { if (points == null || points.length == 0 || points[0].length == 0) { return true; } double minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; HashMap<Integer, List<Point>> map = new HashMap<Integer, List<Point>>(); for (int[] point: points) { if (point[0] < minX) { minX = (double)point[0]; } if (point[0] > maxX) { maxX = (double)point[0]; } if (!map.containsKey(point[0])) map.put(point[0], new ArrayList<Point>()); map.get(point[0]).add(new Point(point[0], point[1])); } double mid = minX + (maxX - minX) / 2; for (int[] point: points) { double reflect = mid + mid - point[0]; boolean find = false; if (map.containsKey((int)reflect)) { for (Point p: map.get((int)reflect)) { if (point[1] == p.y) { find = true; } } if (find == false) { return false; } } else { return false; } } return true; }}有两点可以改进:第一,改用HashSet.add(Arrays.hashCode(point)) 存点;第二,求对称点时,用minX + maxX求出和,因为是对称点,中点都是一样的,那么sum也肯定是一样的,sum减其中一个点的x,就是另一个点的x。代码如下:
public class Solution { public boolean isReflected(int[][] points) { HashSet<Integer> pointSet = new HashSet<>(); int sum; int maxX, minX; minX = Integer.MAX_VALUE; maxX = Integer.MIN_VALUE; for(int[] point:points) { maxX = Math.max(maxX, point[ 0 ]); minX = Math.min(minX, point[ 0 ]); pointSet.add(Arrays.hashCode(point)); } sum = maxX+minX; for(int[] point:points) { if(!pointSet.contains(Arrays.hashCode(new int[]{sum-point[ 0 ], point[ 1 ]}))) { return false; } } return true; }}
0 0
- LeetCode 356. Line Reflection
- LeetCode 356. Line Reflection
- 356. Line Reflection
- Line Reflection
- Line Reflection
- LeetCode 356. Line Reflection(线反射)
- [leetcode] 356. Line Reflection 解题报告
- [Leetcode] 356. Line Reflection 解题报告
- Reflection
- Reflection
- Reflection
- Reflection
- Reflection
- Reflection
- Reflection
- Reflection
- LINE
- line
- Html5 部分快捷键
- hibernate-基础原理(2)
- tensorflow学习(一)tensorflow-GPU安装(Driver375.26+CUDA8.0.61+CUDNN5.1)
- linux文件系统详解
- Activiti 介绍
- 356. Line Reflection
- 对一个deb包的解压、修改、重新打包全过程方法
- 在使用了spring的web项目中进行junit单元测试
- Vue2.0 transition | demo 实践填坑
- bzoj3143 游走 [高斯消元+概率]
- springmvc ModelAndView传值
- 五、关于自定义view的文章:雷达图
- 链接脚本文件的写法
- [HDU] 1106 排序