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 小时前
leetcode 3629. 通过质数传送到达终点的最少跳跃次数 中等
leetcode
圣保罗的大教堂1 小时前
leetcode 1914. 循环轮转矩阵 中等
leetcode
wabs6663 小时前
关于二叉树【力扣100.相同的树的思考】
数据结构·c++·算法·leetcode·二叉树·递归法
alphaTao3 小时前
LeetCode 每日一题 2026/9/14-2026/9/20
算法·leetcode
hanlin033 小时前
刷题笔记:力扣第560题-和为k的子数组
笔记·算法·leetcode
Navigator_Z16 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
语戚17 小时前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp
青山木17 小时前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
这料鬼有毒19 小时前
二刷hot100-1143.最长公共子序列
算法·leetcode·动态规划
chenqianghqu1 天前
go语言SDK升级到1.27更新调试
golang