zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    第一次用python 写的简单爬虫 记录在自己的博客
    【转】使用notepad运行python
    Android Tools&Cmd
    箴言
    无问西东
    Unity存储路径
    手机屏幕亮度设定
    Go Lang
    iOS .tbd
    Prime31
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6185515.html
Copyright © 2011-2022 走看看