Ai
4 Star 12 Fork 8

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

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
closestPair.go 1.65 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"
"math"
"sort"
)
// 此函数在给定的一组 2D 点中找到最近的一对点
// 输入参数是一个二维点数组,表示为两个整数的切片
func closestPair(points [][]int) float64 {
// 创建一个长度等于输入点数的辅助切片
h := make(helper, len(points))
// 对于每个点,使用勾股定理计算其与原点 (0,0) 的距离
// 将点的距离和索引存储在辅助切片中
for i, v := range points {
h[i] = [2]float64{math.Hypot(float64(v[0]), float64(v[1])), float64(i)}
}
// 按距离的升序对辅助切片进行排序
sort.Sort(h)
// 如果至少有一个点,则返回最近的一对之间的距离
if len(h) >= 1 {
return h[0][0]
}
// 如果没有积分,则返回 0
return 0
}
// helper 类型定义为 float64 对的切片
type helper [][2]float64
// 以下方法实现了 helper 类型的 sort.Interface 接口
// 交换辅助切片中的两个元素
func (h helper) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
// 比较两点之间的距离
func (h helper) Less(i, j int) bool {
return h[i][0] < h[j][0]
}
// 返回辅助切片的长度
func (h helper) Len() int {
return len(h)
}
func main() {
points := [][]int{{3, 3}, {5, -1}, {-2, 4}}
res := closestPair(points)
fmt.Println(res)
}
//$ go run closestPair.go
//4.242640687119286
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助