脚本宝典收集整理的这篇文章主要介绍了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个即可。
最终代码
<?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);
}
}
若觉得本文章对你有用,欢迎用爱发电资助。
以上是脚本宝典为你收集整理的Leetcode PHP题解--D29 973. K Closest Points to Origin全部内容,希望文章能够帮你解决Leetcode PHP题解--D29 973. K Closest Points to Origin所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。