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}
}
相关推荐
小雅痞1 小时前
[Java][Leetcode hard] 135. 分发糖果
java·算法·leetcode
黑牛儿1 小时前
Swoole协程 vs Go协程:PHP开发者一看就懂的实战对比
后端·golang·php·swoole
嘻嘻哈哈樱桃1 小时前
数据流中的中位数 力扣--160
算法·leetcode·职场和发展
j_xxx404_1 小时前
力扣算法题:字符串(最长公共前缀|最长回文子串)
c++·算法·leetcode
人道领域2 小时前
【LeetCode刷题日记】:344,541-字符串反转字符串反转技巧:双指针原地交换法
算法·leetcode·面试
Wenweno0o10 小时前
Eino-Document 组件使用指南
golang·大模型·智能体·eino
木子墨51610 小时前
LeetCode 热题 100 精讲 | 并查集篇:最长连续序列 · 岛屿数量 · 省份数量 · 冗余连接 · 等式方程的可满足性
数据结构·c++·算法·leetcode
lolo大魔王14 小时前
Go语言的反射机制
开发语言·后端·算法·golang
故事和你9115 小时前
洛谷-算法1-7-搜索3
数据结构·c++·算法·leetcode·动态规划
XMYX-016 小时前
16 - Go 协程(goroutine):从基础到实战
开发语言·golang