Leetcode 356. Line Reflection

題目:ide

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.

解法:code

這道題主要是判斷N個點是否沿某條線對稱,能夠從提示看出來全部的點應該要知足 2Y = minX + maxX;因此先把全部的點掃一遍存下來,找到minX和minX. 而後再掃一遍,斷定是否點都是延直線對稱的。 時間複雜度O(n),空間複雜度O(n).it

代碼:io

public class Solution {
    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;
    }
}
相關文章
相關標籤/搜索