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}
}
相关推荐
枫景Maple9 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
roman_日积跬步-终至千里12 小时前
【Go语言基础【9】】字符串格式化与输入处理
golang
緈福的街口12 小时前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
小刘不想改BUG15 小时前
LeetCode 70 爬楼梯(Java)
java·算法·leetcode
比特森林探险记16 小时前
Go 中的 Map 与字符处理指南
c++·算法·golang
比特森林探险记16 小时前
Go 中 map 的双值检测写法详解
java·前端·golang
哆啦A梦158817 小时前
在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/[email protected] 更换为 go-ansible/@v1.1.7
开发语言·golang·ansible
LanLance17 小时前
ES101系列09 | 运维、监控与性能优化
java·运维·后端·elasticsearch·云原生·性能优化·golang
sz66cm18 小时前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先