Ai
4 Star 12 Fork 8

ShirDon-廖显东/零基础Go语言算法实战源码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
interview10-3.go 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
ShirDon-廖显东 提交于 2024-04-22 14:56 +08:00 . first commit
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++
package main
import "fmt"
func ClosestPair(points [][]int, K int) [][]int {
if len(points) == K {
return points
}
var v []int
var re [][]int
m := make(map[int]int)
for i := 0; i < len(points); i++ {
m[i] = points[i][0]*points[i][0] + points[i][1]*points[i][1]
v = append(v, i)
}
closestUtil(m, v, 0, len(v)-1, K)
for i := 0; i < K; i++ {
re = append(re, points[v[i]])
}
return re
}
func closestUtil(m map[int]int, s []int, start, end, k int) {
p := m[s[end]]
l := start
for i := start; i < end; i++ {
if m[s[i]] < p {
s[l], s[i] = s[i], s[l]
l++
}
}
s[l], s[end] = s[end], s[l]
if k == l {
return
} else if l < k {
closestUtil(m, s, l+1, end, k)
} else {
closestUtil(m, s, start, l-1, k)
}
}
func main() {
points := [][]int{{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}
k := 2
res := ClosestPair(points, k)
fmt.Println(res)
}
//$ go run interview10-1.go
//[[2 3] [3 4]]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助