Java | Leetcode Java题解之第497题非重叠矩形中的随机点

题目:

题解:

java 复制代码
class Solution {
    Random rand;
    List<Integer> arr;
    int[][] rects;

    public Solution(int[][] rects) {
        rand = new Random();
        arr = new ArrayList<Integer>();
        arr.add(0);
        this.rects = rects;
        for (int[] rect : rects) {
            int a = rect[0], b = rect[1], x = rect[2], y = rect[3];
            arr.add(arr.get(arr.size() - 1) + (x - a + 1) * (y - b + 1));
        }
    }

    public int[] pick() {
        int k = rand.nextInt(arr.get(arr.size() - 1));
        int rectIndex = binarySearch(arr, k + 1) - 1;
        k -= arr.get(rectIndex);
        int[] rect = rects[rectIndex];
        int a = rect[0], b = rect[1], y = rect[3];
        int col = y - b + 1;
        int da = k / col;
        int db = k - col * da;
        return new int[]{a + da, b + db};
    }

    private int binarySearch(List<Integer> arr, int target) {
        int low = 0, high = arr.size() - 1;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            int num = arr.get(mid);
            if (num == target) {
                return mid;
            } else if (num > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return low;
    }
}
相关推荐
happymaker06265 小时前
LeetCodeHot100——1.两数之和(详细解答)
java·数据结构·学习·算法
AI人工智能+电脑小能手5 小时前
【大白话说Java面试题 第60题】【JVM篇】第20题:垃圾收集算法和垃圾收集器有什么区别?
java·jvm·算法·面试
@ray3215 小时前
LeetCode Hot 100 — C++ 题解
c++·算法·leetcode
wand codemonkey5 小时前
(三十)web应用+【核心】+【规矩】+【原理】
java·开发语言·前端
逸Y 仙X5 小时前
文章三十三:Elasticsearch 文本分词器深入实战
java·大数据·elasticsearch·搜索引擎·全文检索
吴声子夜歌5 小时前
状态机——并行分支聚合
java·状态机·分支聚合
optimistic_chen7 小时前
【AI Agent 全栈开发】MCP
java·linux·运维·人工智能·ai编程·mcp
2401_8332693014 小时前
Java网络编程入门
java·开发语言
金銀銅鐵15 小时前
[Java] 如何将 Lambda 表达式对应的类保存到 class 文件中?
java·后端
それども15 小时前
Gradle 构建疑难杂症 Could not find netty-transport-native-epoll-linux-aarch_64.ja
java·服务器·gradle·maven