Leetcode PHP题解--D29 973. K Closest Points to Origin
生活随笔
收集整理的這篇文章主要介紹了
Leetcode PHP题解--D29 973. K Closest Points to Origin
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
973. K Closest Points to Origin
題目鏈接
973. K Closest Points to Origin
題目分析
給一個坐標數組points,從中返回K個離0,0最近的坐標。
其中,用歐幾里得距離計算。
思路
把距離作為數組的鍵,把對應坐標作為數組的值。
用ksort函數排序,再用array_slice函數獲取前K個即可。
最終代碼
class Solution {function kClosest($points, $K) {$dists = [];foreach($points as $point){$dists[(string)sqrt(pow($point[0],2)+pow($point[1],2))] = $point;}ksort($dists);return array_slice($dists,0,$K);} } 復制代碼若覺得本文章對你有用,歡迎用愛發電資助。
總結
以上是生活随笔為你收集整理的Leetcode PHP题解--D29 973. K Closest Points to Origin的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET -- WebForm -
- 下一篇: 新手入门之VIM 编辑小技巧