zoukankan      html  css  js  c++  java
  • [Swift]LeetCode973. 最接近原点的 K 个点 | K Closest Points to Origin

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

    (Here, the distance between two points on a plane is the Euclidean distance.)

    You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.) 

    Example 1:

    Input: points = [[1,3],[-2,2]], K = 1
    Output: [[-2,2]]
    Explanation: 
    The distance between (1, 3) and the origin is sqrt(10).
    The distance between (-2, 2) and the origin is sqrt(8).
    Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
    We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
    

    Example 2:

    Input: points = [[3,3],[5,-1],[-2,4]], K = 2
    Output: [[3,3],[-2,4]]
    (The answer [[-2,4],[3,3]] would also be accepted.) 

    Note:

    1. 1 <= K <= points.length <= 10000
    2. -10000 < points[i][0] < 10000
    3. -10000 < points[i][1] < 10000

    我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。

    (这里,平面上两点之间的距离是欧几里德距离。)

    你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。 

    示例 1:

    输入:points = [[1,3],[-2,2]], K = 1
    输出:[[-2,2]]
    解释: 
    (1, 3) 和原点之间的距离为 sqrt(10),
    (-2, 2) 和原点之间的距离为 sqrt(8),
    由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。
    我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]。
    

    示例 2:

    输入:points = [[3,3],[5,-1],[-2,4]], K = 2
    输出:[[3,3],[-2,4]]
    (答案 [[-2,4],[3,3]] 也会被接受。) 

    提示:

    1. 1 <= K <= points.length <= 10000
    2. -10000 < points[i][0] < 10000
    3. -10000 < points[i][1] < 10000

    1004ms
     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3          guard K < points.count else { return points }
     4 
     5     var distanceDict : [Int: [Int]] = [:]
     6     for point in points {
     7         let distance = point[0]*point[0] + point[1]*point[1]
     8         distanceDict[distance] = point
     9     }
    10 
    11     var allDistance = Array<Int>(distanceDict.keys)
    12     findKElement(&allDistance, 0, allDistance.count - 1, K)
    13     var kClosest: [[Int]] = []
    14     for i in 0..<K {
    15         kClosest.append(distanceDict[allDistance[i]]!)
    16     }
    17     return kClosest
    18     }
    19     
    20     
    21     func findKElement(_ arr: inout [Int], _ start: Int, _ end: Int, _ k: Int) {
    22   
    23     let indexP: Int = position(&arr, start, end)
    24     
    25     if indexP == k {
    26         return 
    27     }else if indexP < k {
    28          findKElement(&arr, indexP+1, end, k)
    29     }else {
    30          findKElement(&arr, start, indexP-1, k)
    31     }
    32 }
    33 
    34 func position(_ arr: inout [Int], _ start: Int, _ end: Int) -> Int {
    35     var i = start - 1
    36     var j = start
    37     let pivot = arr[end]
    38     while j < end {
    39         if arr[j] <= pivot {
    40             i += 1
    41             arr.swapAt(i, j)
    42         }
    43         j += 1
    44     }
    45 
    46     arr.swapAt(i+1, end)
    47     return i+1
    48   }
    49 }

    1052ms

     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3     func distance(_ p: [Int]) -> Int {
     4         return p[0] * p[0] + p[1] * p[1]
     5     }
     6     
     7     let sorted = points.sorted(by: { (p1, p2) -> Bool in
     8         return distance(p1) < distance(p2)
     9     })
    10     return Array(sorted[0..<K])
    11   }
    12 }

    1056ms

     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3         var closest = points.map{
     4             (($0[0] * $0[0] + $0[1] * $0[1]), $0)
     5         }
     6         
     7         closest.sort{ $0.0 < $1.0 }
     8         var res: [[Int]] = []
     9         for i in 0..<K {
    10             res.append(closest[i].1)
    11         }
    12         
    13         return res
    14     }
    15 }

    1060ms

     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3         var result = [(distance: Double, point: [Int])]()
     4         
     5         for point in points {
     6             let distance = sqrt((pow(Double(point[0]), 2) + pow(Double(point[1]), 2)))
     7             result.append((distance, point))
     8         }
     9         
    10         result.sort(by: { $0.distance < $1.distance })
    11         
    12         return result[0..<K].compactMap({ $0.point })
    13     }
    14 }

    1063ms

    1 class Solution {
    2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
    3         let sortted = points.sorted { (a, b) -> Bool in
    4             return (a[0] * a[0] + a[1] * a[1]) < (b[0] * b[0] + b[1] * b[1])
    5         }
    6         return Array(sortted.prefix(K))
    7     }
    8 }

    1064ms 

     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3         var points = points
     4         points.sort(by:sortArray)
     5         var ret:[[Int]] = [[Int]]();
     6         for i in 0..<K
     7         {
     8             ret.append(points[i])
     9         } 
    10         return ret
    11     }
    12     
    13     func sortArray(_ a:[Int],_ b:[Int]) -> Bool
    14     {
    15         var da:Int = a[0]*a[0]+a[1]*a[1]
    16         var db:Int = b[0]*b[0]+b[1]*b[1]
    17         return da < db        
    18     }
    19 }

    1076ms

    1 class Solution {
    2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
    3         let pts = points.sorted { $0[0]*$0[0]+$0[1]*$0[1] < $1[0]*$1[0]+$1[1]*$1[1] }
    4         // print(pts)
    5         return Array(pts[0..<K])
    6     }
    7 }

    1080ms

     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3         let pointsAndEuclidean = points.map({ (point: [Int]) -> ([Int], Double) in
     4             let  sqrtee = pow(Double(point[0]), 2)
     5                 + pow(Double(point[1]), 2)
     6             return (point, sqrt( sqrtee ))
     7         })
     8         return pointsAndEuclidean.sorted(by: { $0.1 < $1.1 })[..<K].map({ $0.0 })
     9     }
    10 }

    1100ms

     1 class Solution {
     2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
     3         var result = [([Int],Double)]()
     4         for p in points {
     5             let dist = (pow(Double(p[0]),2)+pow(Double(p[1]),2)).squareRoot()
     6             result.append((p, dist))
     7         }
     8         result.sort(by: {
     9             return $0.1 < $1.1
    10         })
    11         return Array(result.map { $0.0 }[0..<K])
    12     }
    13 }

    1120ms

    1 class Solution {
    2     func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
    3         let distances = points.map { sqrt(Double(($0[0] * $0[0]) + ($0[1] * $0[1]))) }
    4         return zip(points, distances).sorted { $0.1 < $1.1 }.prefix(K).map { $0.0 }
    5     }
    6 }
  • 相关阅读:
    SQLite在iOS开发中的使用
    实现序列化和反序列化
    NSPredicate用于对集合类中的元素进行筛选
    通知中心NSNotification与委托的异同,需要注意的要点
    OC 重写description,isEqual方法
    iOs 单例模式的定义,实现、步骤
    Obejctiv-c 里面KVC 和 KVO的实现步骤,和有关方法
    关于NSTimer的几种构建方式
    NSTimer 实现到一个指定时间(年、月、日)的倒计时
    关于UILable、UIButton、UITextField简单运用
  • 原文地址:https://www.cnblogs.com/strengthen/p/10262303.html
Copyright © 2011-2022 走看看