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}
}
相关推荐
2501_9419820510 分钟前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信
alphaTao1 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习1 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
不知名XL2 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––2 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao3 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
cpp_25014 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25014 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder1234 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
cpp_25014 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷