当前位置:网站首页>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
}
}
}
边栏推荐
- 移除区间(贪心)
- Les neuf caractéristiques de la parole et les neuf temps en anglais
- Common formatting methods for amount numbers
- [world history] Episode 1: people in the Stone Age
- 广发易淘金和同花顺哪个更好,更安全一些
- Biscuit distribution
- Add a string at the input and textarea cursors
- Two common ways for orcale to clear table data
- Deconstruction assignment of variables
- 网上股票开户安不安全?有谁知道呢
猜你喜欢

Shell array

Gif动图如何裁剪?收下这个图片在线裁剪工具

从0到1完全掌握 XSS

使用sphinx根据py源文件自动生成API文档

Does stream even have application advanced learning? As a programmer, you know what

How to view the Chrome browser plug-in location

弹性布局(display:flex;)属性详解

Experts' suggestions | 8 measures to accelerate your innovative career planning and growth

Shell built-in commands

China has made major breakthroughs in battery technology. Japan, South Korea and the United States are lagging behind. China has consolidated its leading edge
随机推荐
One time summary: 64 common terms for data analysis!
What is the safest app for stock account opening? Tell me what you know
NBD Network Block Device
Nine parts of speech and nine tenses in English
Jaspersoft studio installation
分享自己平時使用的socket多客戶端通信的代碼技術點和軟件使用
Les neuf caractéristiques de la parole et les neuf temps en anglais
买卖股票的最佳时机
挖财是正规的吗?股票开户安全吗?
JGG | overview of duhuilong group of Hebei University Research on plant pan genomics
让PyTorch训练速度更快,你需要掌握这17种方法
【世界历史】第二集——文明的曙光
如何裁剪动图大小?试试这个在线照片裁剪工具
For the first time in China, Chinatelecom 5g underground personnel positioning project is officially commercial: it can track the position in real time to ensure operation safety
Why should programmers be softer?
Pourquoi les programmeurs devraient - ils être plus doux?
QQ情话糖果情话内容获取并保存
JVM uses tools to analyze classic cases of OOM
[untitled]
Async await to achieve sleep waiting effect