973. K Closest Points to Origin
package LeetCode_973 import java.util.* /** * 973. K Closest Points to Origin * https://leetcode.com/problems/k-closest-points-to-origin/description/ * * We have a list of points on the plane. Find the K closest points to the origin (0, 0). (Here, the distance between two points on a plane is the Euclidean distance.) You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) Example 1: Input: points = [[1,3],[-2,2]], K = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. * */ class Solution { /* * solution: PriorityQueue, Time complexity:O(nlogk), Space complexity:O(1) * because heapify: O(logk), k is size of PriorityQueue * */ fun kClosest(points: Array<IntArray>, K: Int): Array<IntArray>? { //sort by distance ascending val minHeap = PriorityQueue<IntArray> { a, b -> distance(b) - distance(a) } for (point in points) { minHeap.add(point) if (minHeap.size > K) { minHeap.poll() } } val result = Array(K, { IntArray(2) }) for (i in minHeap.indices) { result[i] = minHeap.poll() } return result } private fun distance(array: IntArray): Int { return array[0] * array[0] + array[1] * array[1] } }
标签:
PriorityQueue
, leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)