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}
}
相关推荐
VT.馒头22 分钟前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
毅炼1 小时前
hot100打卡——day17
java·数据结构·算法·leetcode·深度优先
Tisfy1 小时前
LeetCode 3010.将数组分成最小总代价的子数组 I:排序 OR 维护最小次小
算法·leetcode·题解·排序·最小次小值
草履虫建模3 小时前
力扣算法 121. 买卖股票的最佳时机
算法·leetcode·职场和发展·贪心算法·动态规划·一次遍历
爱尔兰极光3 小时前
LeetCode--有序数组的平方
算法·leetcode·职场和发展
haluhalu.3 小时前
LeetCode---基础算法刷题指南
数据结构·算法·leetcode
iAkuya4 小时前
(leetcode)力扣100 58组合总和(回溯)
算法·leetcode·职场和发展
bing.shao4 小时前
Golang 开发者视角:解读《“人工智能 + 制造” 专项行动》的技术落地机遇
人工智能·golang·制造
ONE_PUNCH_Ge4 小时前
Go 语言泛型
开发语言·后端·golang
爱尔兰极光4 小时前
LeetCode--移除元素
算法·leetcode·职场和发展