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}
}
相关推荐
人道领域39 分钟前
【LeetCode刷题日记】二叉树翻转:递归与迭代全解析
java·算法·leetcode
进击的荆棘1 小时前
递归、搜索与回溯——综合(上)
c++·算法·leetcode·深度优先·dfs
平凡但不平庸的码农8 小时前
Go Slice 详解
算法·golang
风筝在晴天搁浅12 小时前
快手/字节 CodeTop LeetCode 415.字符串相加
算法·leetcode
米粒114 小时前
力扣算法刷题 Day 64 Floyd算法 & A* 算法 & 总结篇
算法·leetcode·职场和发展
jieyucx17 小时前
零基础入门:一文看懂哈希算法、哈希表与 Go map
golang·哈希算法·散列表·map·哈希表
Liangwei Lin17 小时前
LeetCode 41. 缺失的第一个正数
数据结构·算法·leetcode
小雅痞18 小时前
[Java][Leetcode hard] 76. 最小覆盖子串
java·算法·leetcode
ulias21219 小时前
leetcode热题 - 6
linux·算法·leetcode
li星野20 小时前
栈与队列通关八题:从括号匹配到接雨水,手撕LeetCode高频题(Python + C++)
c++·python·leetcode