Leetcode: 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:

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.

本题精妙之处在于:1. 如何最快找到possible的line的x axis(我最开始想到要用quickselect find median的方法,结果别人有min max方法)

2. 如何最方便确定一个点关于该line的reflection是否存在,由于既有x又有y,不太好处理,别人有个聪明的办法把x跟y组合成string,然后用hashset

学到了:以后处理多个value共同作用的时候,可以考虑wrapper class(但是不好用set), 更应该想一想能不能直接把它们组合成string(直接又好利用set来find)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值