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.

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.

Tips:

O(n)

  1. If there exists a line reflecting the points, then each pair of symmetric points will have their x coordinates adding up to the same value, including the pair with the maximum and minimum x coordinates.
  2. So, in the first pass, I iterate through the array, adding each point to the hash set, and keeping record of the minimum and maximum x coordinates.
  3. Then, in the second pass, I check for every point to the left of the reflecting line, if its symmetric point is in the point set or not.
  4. If all points pass the test, then there exists a reflecting line. Otherwise, not.
  5. Use String to encode the coordinates.

Code:

public class Solution {
    public boolean isReflected(int[][] points) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        HashMap<Integer, HashSet<Integer>> map = new HashMap<>();
        for(int[] p:points){
            max = Math.max(max,p[0]);
            min = Math.min(min,p[0]);
            if (!map.containsKey(p[0])) map.put(p[0], new HashSet<>());
            HashSet<Integer> set = map.get(p[0]);
            set.add(p[1]);
            map.put(p[0], set);
        }
        int sum = max+min;
        for(int[] p:points){
            if( !map.containsKey(sum - p[0]) || !map.get(sum - p[0]).contains(p[1]))
                return false;
        }
        return true;
    }
}

String,无set

public class Solution {
    public boolean isReflected(int[][] points) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        HashSet<String> set = new HashSet<>();
        for(int[] p:points){
            max = Math.max(max,p[0]);
            min = Math.min(min,p[0]);
            String str = p[0] + "a" + p[1];
            set.add(str);
        }
        int sum = max+min;
        for(int[] p:points){
            String str = (sum-p[0]) + "a" + p[1];
            if( !set.contains(str))
                return false;

        }
        return true;
    }
}

results matching ""

    No results matching ""