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}
}
相关推荐
逝雪Yuki31 分钟前
Leetcode——11. 盛最多水的容器
c++·算法·leetcode·双指针
岁忧9 小时前
macOS配置 GO语言环境
开发语言·macos·golang
薰衣草233311 小时前
一天两道力扣(6)
算法·leetcode
逝雪Yuki11 小时前
Leetcode——287. 寻找重复数
c++·leetcode·二分查找·双指针·环形链表
科大饭桶12 小时前
数据结构自学Day13 -- 快速排序--“前后指针法”
数据结构·算法·leetcode·排序算法·c
java叶新东老师14 小时前
goland编写go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案
开发语言·后端·golang
@蓝莓果粒茶14 小时前
LeetCode第350题_两个数组的交集II
c++·python·学习·算法·leetcode·职场和发展·c#
设计师小聂!14 小时前
力扣热题100----------53最大子数组和
java·数据结构·算法·leetcode
艾莉丝努力练剑15 小时前
【LeetCode&数据结构】二叉树的应用(二)——二叉树的前序遍历问题、二叉树的中序遍历问题、二叉树的后序遍历问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
YuTaoShao16 小时前
【LeetCode 热题 100】51. N 皇后——回溯
java·算法·leetcode·职场和发展