Ai
4 Star 12 Fork 8

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

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
interview8-2.go 1.20 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/rand"
"time"
)
type Solution struct {
values []int
maxValue int
}
func NewSolution(w []int) Solution {
values := []int{}
current := 0
for _, v := range w {
current += v
values = append(values, current)
}
rand.Seed(time.Now().UnixNano())
return Solution{
values: values,
maxValue: current,
}
}
func (s *Solution) PickIndex() int {
num := rand.Intn(s.maxValue)
return findGreater(s.values, num)
}
// 二分查找较大的值
func findGreater(values []int, num int) int {
l, r := 0, len(values)-1
for l <= r {
m := (l + r) >> 1
if values[m] > num {
r = m - 1
} else {
l = m + 1
}
}
return l
}
func main() {
array := []int{1, 2, 9, 20, 31, 45, 63, 70, 100}
res := NewSolution(array)
fmt.Println(res.maxValue)
fmt.Println(res.values)
}
//$ go run interview7-2.go
//341
//[1 3 12 32 63 108 171 241 341]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助