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;
    }
}
相关推荐
木井巳18 小时前
[Java数据结构和算法] HashMap 和 HashSet
java·数据结构·1024程序员节
祈祷苍天赐我java之术19 小时前
解析常见的限流算法
java·数据结构·算法
摇滚侠19 小时前
IDEA 启动前端项目 IDEA 切换分支
java·ide·intellij-idea
元直数字电路验证19 小时前
Jakarta EE开发中,如何配置IntelliJ IDEA的远程调试?
java·eureka·intellij-idea
石头wang19 小时前
idea字体的问题(idea应用本身的字体问题)
java·ide·intellij-idea
孔明兴汉20 小时前
第一章-第三节-Java开发环境配置
java·开发语言
小王不爱笑13221 小时前
Java 核心知识点查漏补缺(一)
java·开发语言·python
空空kkk21 小时前
Java——类和对象
java·开发语言
JIngJaneIL21 小时前
篮球论坛|基于SprinBoot+vue的篮球论坛系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·篮球论坛系统
毕设源码-赖学姐21 小时前
【开题答辩全过程】以 安卓的服装销售APP为例,包含答辩的问题和答案
java·eclipse·tomcat