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}
}
相关推荐
阑梦清川23 分钟前
关于Go语言的开发环境的搭建
开发语言·后端·golang
言之。28 分钟前
Makefile 在 Go 项目中的实践
开发语言·elasticsearch·golang
MoonBit月兔2 小时前
插件双更新:LeetCode 刷题支持正式上线,JetBrains IDE 插件持续升级!
ide·算法·leetcode
袁气满满~_~4 小时前
LeetCode:617、合并二叉树
算法·leetcode·二叉树
边跑边掩护4 小时前
LeetCode 820 单词的压缩编码题解
算法·leetcode·职场和发展
Espresso Macchiato4 小时前
Leetcode 3543. Maximum Weighted K-Edge Path
leetcode·leetcode medium·图遍历·leetcode 3543·leetcode双周赛156
Clown954 小时前
go-zero(十八)结合Elasticsearch实现高效数据检索
开发语言·elasticsearch·golang
爱coding的橙子5 小时前
每日算法刷题计划Day7 5.15:leetcode滑动窗口4道题,用时1h
算法·leetcode
阳洞洞6 小时前
leetcode 56. 合并区间
leetcode
小刘不想改BUG6 小时前
LeetCode LCR 015. 找到字符串中所有字母异位词 (Java)
linux·算法·leetcode