当前位置:网站首页>15 -- k points closest to the origin
15 -- k points closest to the origin
2022-06-25 14:43:00 【JH_ Cao】
subject
Github link
Closest to the origin K A little bit
Given an array points , among points[i] = [xi, yi] Express X-Y A point on the plane , And is an integer k , Return from origin (0,0) Current k A little bit .
here , The distance between two points on the plane is Euclid distance ( √(x1 - x2)2 + (y1 - y2)2 ).
You can press In any order Return to the answer . In addition to the order of point coordinates , answer Make sure yes only Of .

- Ideas
- Of course you can sort , Find the front again K Number
- But this problem mainly focuses on building piles , This is the classic topK problem , at the idea of topK problem , You have to think about building a heap
- So here comes the question , Build a small top pile or a large top pile ?
- First remember the pithy formula :
topK Small , Big pile top ;topK Big , Small cap pile
- Why is that so ?
(1) Because of the demand topK When I was a child , Build a large top pile , The top element of the heap is this topK The biggest element in the small , This makes it easy for the following elements to compare ;for instance ,[2,4,6,5,1] in , Seek before top3 Small value
Build a large top pile , The length of the heap is 3
Easy to come by : The top of the pile is 6, Zuo Wei 2, Right for 4,
The current heap is :[6,2,4]
When new elements 5 Come in and build a pile , When comparing
Take out the top element first 6 To compare , Find out 6 Than 5 Big ,
(a) Then add to the array obtain : [6,2,4,5]
(b) Then swap the first and last elements of the array , obtain : [5,2,4,6]
(c) Delete the last element , obtain : [5,2,4]
This is the latest heap , And so on
(d) When 1 To build the reactor , obtain : [1,2,4]
To this end , obtain top3 The small element is [1,2,4]
(2) seek topK Big , Build a small top pile , The principle is similar to the above .
- answer
- The code of this problem :
class facebook03 {
// Find the least distance topK, Build a large top pile
// The top element of the heap , yes topK The last , in other words , Value after , Compare , Just compare it to the top element
// That's why , seek topK Small , Build a large top pile
// On the other hand , If o topK Big , Just build a small top pile
// Sum up the memory formula : topK Big , Small cap pile ;topK Small , Big pile top
var lock = NSLock()
func kClosest(_ points: [[Int]], _ k: Int) -> [[Int]] {
let heap = MyHeap(k)
for i in 0..<points.count {
let curPoint = points[i]
lock.lock()
let val = helper(curPoint) //[[6,10],[-3,3],[-2,5],[0,2]]
print(i,"--",val)
heap.createHeap([i: val])
lock.unlock()
}
var res = [[Int]]()
for i in 0..<k {
let ele = heap.heapArr[i]
let index = ele.first!.key
res.append(points[index])
}
return res
}
func helper(_ p:[Int]) -> Int {
return p[0] * p[0] + p[1] * p[1]
}
}
class MyHeap {
var heapArr = [[Int: Int]]()
var topK: Int!
init(_ top: Int) {
topK = top
}
func createHeap(_ dict: [Int: Int]) {
if heapArr.count < topK {
heapArr.append(dict)
siftUp(heapArr.count - 1)
} else {
if !compare(dict, heapArr[0]) {
heapArr.append(dict)
heapArr.swapAt(0, heapArr.count - 1)
heapArr.removeLast()
siftDown(0)
}
}
}
private func siftUp(_ index: Int) {
if index < 1 {
return
}
let parent = (index - 1) / 2
if compare(heapArr[index], heapArr[parent]) {
heapArr.swapAt(parent, index)
siftUp(parent)
}
}
private func siftDown(_ index: Int) {
var left = index * 2 + 1
var right = index * 2 + 2
var parent = index
if left < heapArr.count && !compare(heapArr[parent], heapArr[left]) {
swap(&parent, &left)
}
if right < heapArr.count && !compare(heapArr[parent], heapArr[right]) {
swap(&parent, &right)
}
if parent != index {
heapArr.swapAt(parent, index)
siftDown(parent)
}
}
private func compare(_ ele1: [Int: Int], _ ele2: [Int: Int]) -> Bool {
if ele1.first!.value > ele2.first!.value {
return true
} else {
return false
}
}
}
边栏推荐
- 程序员为什么要软一点?
- Nine parts of speech and nine tenses in English
- Stream竟然还有应用进阶学习?作为程序员的你知道吗
- HMS core machine learning service realizes simultaneous interpretation, supports Chinese-English translation and multiple voice broadcast
- 112页机器学习-数学基础回顾.pptx
- Explanation of dev/mapper
- 两种方法实现pycharm中代码回滚到指定版本(附带截图展示)
- Why should programmers be softer?
- Partager les points techniques de code et l'utilisation de logiciels pour la communication Multi - clients socket que vous utilisez habituellement
- 【世界历史】第一集——石器时代的人们
猜你喜欢

程序员为什么要软一点?

合宙Air32F103CBT6开发板上手报告

JS recursion and while

Sigmoid function sigmoid derivation

API encapsulation of uniapp applet

Application of TSDB in civil aircraft industry

让PyTorch训练速度更快,你需要掌握这17种方法

【Try to Hack】vulhub靶场搭建

Renix perf: detailed explanation of IP network performance test tools and test case parameters

如何裁剪动图大小?试试这个在线照片裁剪工具
随机推荐
[deep learning] multi label learning
China has made major breakthroughs in battery technology. Japan, South Korea and the United States are lagging behind. China has consolidated its leading edge
NBD Network Block Device
Common formatting methods for amount numbers
【中國海洋大學】考研初試複試資料分享
两种方法实现pycharm中代码回滚到指定版本(附带截图展示)
JS to verify whether the string is a regular expression
Gif动图如何裁剪?收下这个图片在线裁剪工具
程序员为什么要软一点?
多张动图怎样合成一张gif?仅需三步快速生成gif动画图片
现在股票开户用什么app最安全?知道的给说一下吧
从0到1完全掌握 XSS
JS recursion and while
To make pytorch faster, you need to master these 17 methods
合宙Air32F103CBT6开发板上手报告
重磅!国产 IDE 发布,由阿里研发,完全开源!(高性能+高定制性)
[untitled]
还没弄明白微服务数据架构事务管理+ACID+一致性+CAP+BASE理论吗,看完彻底解决疑惑
Shell string variable
Power automatic test system nsat-8000, accurate, high-speed and reliable power test equipment