[LeetCode] 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 symmetrically, in other words, answer whether or not if there exists a line that after reflecting all points over the given line the set of the original points is the same that the reflected ones.

Note that there can be repeated points.

Follow up:
Could you do better than O(n^2)?

Example 1:

Input: points = [[1,1],[-1,1]]
Output: true
Explanation: We can choose the line x = 0.

Example 2:

Input: points = [[1,1],[-1,-1]]
Output: false
Explanation: We can't choose a line.

Constraints:

  • n == points.length
  • 1 <= n <= 10^4
  • -10^8 <= points[i][j] <= 10^8

直线镜像。

这道题给的是在一个二维坐标里面给了一堆点的坐标,请问是否存在一条平行于 y 轴的直线,能把这些坐标分成两组,使得所有的坐标都能关于这条直线对称。

这是一道数学题,我这里提供一个 hashset 的做法,需要对 input 数组扫描两次。第一次扫描的时候,我们

  • 记录一下横坐标的最大值和最小值
  • 将每个坐标都变成字符串存入hashmap

第二次扫描的时候,因为我们已经知道横坐标的最大值 max 和最小值 min 了,所以对称轴的横坐标 =  max + min。所以对于 hashset 里的所有横坐标而言,如果能在 hashset 里找的到对应坐标,那么就没问题;一旦找不到对应的坐标,则返回 false。

第 15 行找对应点的横坐标的方法我是这样记的,比如第一个例子,我们有两个点,横坐标分别是 1(max) 和  -1(min)。那么他们的 sum = max + min = 0。所以如果 input 给的所有点都可以两两对应找的到的话,每组点的横坐标应该满足 x1 + x2 = sum。所以对于某一个点来说,求他的对应点的横坐标的做法就是 sum - x1,看看对应点所拼接成的字符串是否在 hashset 里。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean isReflected(int[][] points) {
 3         int max = Integer.MIN_VALUE;
 4         int min = Integer.MAX_VALUE;
 5         HashSet<String> set = new HashSet<>();
 6         for (int[] p : points) {
 7             max = Math.max(max, p[0]);
 8             min = Math.min(min, p[0]);
 9             String str = p[0] + "a" + p[1];
10             set.add(str);
11         }
12 
13         int sum = max + min;
14         for (int[] p : points) {
15             String str = (sum - p[0]) + "a" + p[1];
16             if (!set.contains(str)) {
17                 return false;
18             }
19         }
20         return true;
21     }
22 }

相关题目

356. Line Reflection

447. Number of Boomerangs

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/15101255.html