import java.util.PriorityQueue;
public class Solution {
public int[][] kClosest(int[][] points, int K) {
int len = points.length;
if (len == 0) {
return new int[0][0];
}
// 第 1 步:使用优先队列,动态添加点,lambda 表达式用欧式距离计算点到原点的距离
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(K + 1,
(point1, point2) ->
(point2[0] * point2[0] + point2[1] * point2[1]) - (point1[0] * point1[0] + point1[1] * point1[1]));
for (int[] point : points) {
maxHeap.offer(point);
if (maxHeap.size() > K) {
maxHeap.poll();
}
}
// 第 2 步:将优先队列中的元素输出到结果集列表
int[][] res = new int[K][2];
for (int i = 0; i < K; i++) {
res[i] = maxHeap.poll();
}
return res;
}
}
java-leetcode题解之第972题最接近原点的K个点.zip
需积分: 1 199 浏览量
2024-06-12
05:14:23
上传
评论
收藏 2KB ZIP 举报
![avatar](https://profile-avatar.csdnimg.cn/default.jpg!1)
DdddJMs__135
- 粉丝: 1422
- 资源: 370
最新资源
- 华为HCIA-WLAN 3.0 课程视频(13 WLAN关键报文及STA上线.mp4)
- navicat教程.docx
- 华为HCIA-WLAN 3.0 课程视频(12 CAPWAP隧道.mp4)
- 华为HCIA-WLAN 3.0 课程视频(11 WLAN典型组网方案.mp4)
- 2429550184旺泓-096-1306-SPI接口带字库例程8pin.zip
- 华为HCIA-WLAN 3.0 课程视频(10 WLAN组网架构(下).mp4)
- 华为HCIA-WLAN 3.0 课程视频(09 WLAN组网架构(上).mp4)
- 计算机组成原理-复习提纲
- 华为HCIA-WLAN 3.0 课程视频(08 WLAN基本概念.mp4)
- 华为HCIA-WLAN 3.0 课程视频(07 WLAN的关键技术(下).mp4)
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)