为有牺牲多壮志,敢教日月换新天。

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

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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

 

posted @ 2019-04-20 19:22  为敢技术  阅读(183)  评论(0编辑  收藏  举报