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}
}
相关推荐
代码N年归来仍是新手村成员12 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
踩坑记录12 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
清铎15 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
踩坑记录16 小时前
leetcode hot100 42 接雨水 hard 双指针
leetcode
AlenTech17 小时前
207. 课程表 - 力扣(LeetCode)
算法·leetcode·职场和发展
DICOM医学影像18 小时前
2. go语言从零实现以太坊客户端-查询区块链账户余额
开发语言·golang·区块链·以太坊·web3.0·hardhat
练习时长一年18 小时前
LeetCode热题100(杨辉三角)
算法·leetcode·职场和发展
栈与堆18 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
努力学算法的蒟蒻19 小时前
day58(1.9)——leetcode面试经典150
算法·leetcode·面试
im_AMBER20 小时前
Leetcode 101 对链表进行插入排序
数据结构·笔记·学习·算法·leetcode·排序算法