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解析(225. Implement Stack using Queues)

>> 下一篇: Leetcode基础刷题之PHP解析(150. Evaluate Reverse Polish Notation)