Leetcode PHP题解–D29 973. K Closest Points to Origin

9次阅读

共计 379 个字符,预计需要花费 1 分钟才能阅读完成。

973. K Closest Points to Origin
题目链接
973. K Closest Points to Origin
题目分析
给一个坐标数组 points,从中返回 K 个离 0,0 最近的坐标。
其中,用欧几里得距离计算。
思路
把距离作为数组的键,把对应坐标作为数组的值。
用 ksort 函数排序,再用 array_slice 函数获取前 K 个即可。
最终代码
<?php
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);
}
}
若觉得本文章对你有用,欢迎用爱发电资助。

正文完
 0