356. Line Reflection 解题报告(Medium)

问题:
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)?

解答:
这个解法是看的discuss里的,看着简单,但想到很难。我们要求是不是对称,就是要求每一个点是不是有个点跟它对应。因为可以一个点重复出现,决定我们用hashset来做。记录每一个出现的点,然后再用hashset来找其对应的点。
代码:

public boolean isReflected(int[][] points) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        Set<String> set = new HashSet<String>();
        for (int[] p : points) {
            set.add(p[0] + "," + p[1]);
            min = Math.min(min, p[0]);
            max = Math.max(max, p[0]);
        }

        int sum = min + max;
        for (int[] p : points) {
            if (!set.contains((sum - p[0]) + "," + p[1])) {
                return false;
            }
        }
        return true;
    }
  1. Leetcode Discussion

results matching ""

    No results matching ""