LeetCode 356. Line Reflection(线反射)

这篇博客介绍了LeetCode上的356题——线反射,探讨如何判断2D平面上的点集是否存在关于y轴的反射对称。通过示例解释了判断条件,并提出使用哈希映射优化到O(n)的解题思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题网址:https://leetcode.com/problems/line-reflection/

Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given set of 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.

方法:使用哈希映射来快速查找反射点。

public class Solution {
    public boolean isReflected(int[][] points) {
        if (points == null || points.length == 0) return true;
        Map<List<Integer>, Integer> map = new HashMap<>();
        for(int[] point: points) {
            List<Integer> key = new ArrayList<>(2);
            key.add(point[0]);
            key.add(point[1]);
            Integer count = map.get(key);
            if (count == null) count = 1; else count ++;
            map.put(key, count);
        }
        int mid = 0;
        for(int[] point: points) mid += point[0];
        // mid /= points.length;
        
        while (!map.isEmpty()) {
            List<Integer> key1 = map.keySet().iterator().next();
            Integer count1 = map.get(key1);
            
            if (key1.get(0) * points.length == mid) {
                count1 --;
                if (count1 == 0) map.remove(key1); else map.put(key1, count1);
                continue;
            }

            List<Integer> key2 = new ArrayList<>(2);
            key2.add(2 * mid / points.length - key1.get(0));
            key2.add(key1.get(1));
            
            if (key1.equals(key2)) {
                if (count1 < 2) return false;
                count1 -= 2;
                if (count1 == 0) map.remove(key1); else map.put(key1, count1);
            } else {
                count1 --;
                if (count1 == 0) map.remove(key1); else map.put(key1, count1);

                Integer count2 = map.get(key2);
                if (count2 == null) return false;
                count2 --;
                if (count2 == 0) map.remove(key2); else map.put(key2, count2);
            }
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值