Golang | Leetcode Golang题解之第497题非重叠矩形中的随机点

题目:

题解:

Go 复制代码
type Solution struct {
    rects [][]int
    sum   []int
}

func Constructor(rects [][]int) Solution {
    sum := make([]int, len(rects)+1)
    for i, r := range rects {
        a, b, x, y := r[0], r[1], r[2], r[3]
        sum[i+1] = sum[i] + (x-a+1)*(y-b+1)
    }
    return Solution{rects, sum}
}

func (s *Solution) Pick() []int {
    k := rand.Intn(s.sum[len(s.sum)-1])
    rectIndex := sort.SearchInts(s.sum, k+1) - 1
    r := s.rects[rectIndex]
    a, b, y := r[0], r[1], r[3]
    da := (k - s.sum[rectIndex]) / (y - b + 1)
    db := (k - s.sum[rectIndex]) % (y - b + 1)
    return []int{a + da, b + db}
}
相关推荐
白白白小纯11 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang11 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
圣保罗的大教堂13 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
名字还没想好☜14 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
alphaTao16 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
ttwuai16 小时前
GoFrame 后台日志清空失败:无 WHERE 删除为什么被拦住
前端·golang
进击的程序猿~17 小时前
Go 并发底层原理面试学习指南
开发语言·面试·golang
不在逃避q17 小时前
Golang笔记之Redis
redis·笔记·golang
Hi李耶1 天前
【LeetCode】9-回文数
算法·leetcode·职场和发展
geovindu1 天前
go:loghelper
开发语言·后端·golang