• [Swift]LeetCode356. 直线对称 $ Line Reflection


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址: https://www.cnblogs.com/strengthen/p/10742116.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    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.

    Credits:
    Special thanks to @memoryless for adding this problem and creating all test cases.


    给定一个二维平面上的n个点,找出是否有一条平行于y轴的线反映给定的一组点。

    例1:

    给定点=[[1,1],[-1,1]],返回true。

    例2:

    给定点=[[1,1],[-1,-1]],返回false。

    跟进:

    你能比O(n2)做得更好吗?

    提示:

    1. 找出所有点的最小和最大x值。
    2. 如果有一条线,那么它应该是y=(minx+maxx)/2。
    3. 对于每个点,确保在另一侧有一个反射点。

    信用:

    特别感谢@memoryless添加此问题并创建所有测试用例。


    Solution: 

     1 class Solution{
     2     func isReflected(_ points: [[Int]]) -> Bool
     3     {
     4         if points.isEmpty {return true}
     5         var pts:Set<[Int]> = Set<[Int]>()
     6         var y:Double = 0
     7         for a in points
     8         {
     9             pts.insert(a)
    10             y += Double(a[0])
    11         }
    12         y /=  Double(points.count)
    13         for a in pts
    14         {
    15             if !pts.contains([Int(y * 2) - a[0],a[1]])
    16             {
    17                 return false
    18             }
    19         }
    20         return true
    21     }
    22 }

    点击:Playground测试

    1 print(Solution().isReflected( [[1,1],[-1,1]]))
    2 //Print true
    3 print(Solution().isReflected(  [[1,1],[-1,-1]]))
    4 //Print false
  • 相关阅读:
    LINQ标准查询操作符及例子(转载)
    Winform Combox 下拉模糊匹配
    在RowDataBound事件中取值的几种方法 转载
    shell脚本作业练习题8.6
    7.31.... 简单的python代码
    shell 脚本——第一节课 bash的基本特性
    shell 脚本——第二节课 重定向和管道符
    730
    应用范例:解析 Yahoo 奇摩股市的各档股票资讯HtmlAgilityPack
    微软一个罕为人知的无敌命令
  • 原文地址:https://www.cnblogs.com/strengthen/p/10742116.html
Copyright © 2020-2023  润新知