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}
}
相关推荐
小白程序员成长日记25 分钟前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白27 分钟前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
小白程序员成长日记1 小时前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
他们叫我一代大侠3 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
海琴烟Sunshine4 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
一只鱼^_7 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
Wzx1980129 小时前
go基础语法练习
开发语言·后端·golang
夏鹏今天学习了吗10 小时前
【LeetCode热题100(64/100)】搜索旋转排序数组
算法·leetcode·职场和发展
alphaTao10 小时前
LeetCode 每日一题 2025/11/3-2025/11/9
windows·leetcode
RedJACK~1 天前
Go Ebiten小游戏开发:扫雷
开发语言·后端·golang