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;
    }
}
相关推荐
魔力军3 小时前
Rust学习Day3: 3个小demo实现
java·学习·rust
唐梓航-求职中3 小时前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
时艰.3 小时前
java性能调优 — 高并发缓存一致性
java·开发语言·缓存
落花流水 丶3 小时前
Java 多线程完全指南
java
jxy99983 小时前
mac mini 安装java JDK 17
java·开发语言·macos
YGGP3 小时前
【Golang】LeetCode 1. 两数之和
leetcode
唐梓航-求职中3 小时前
编程大师-技术-算法-leetcode-355. 设计推特
算法·leetcode·面试
biyezuopinvip3 小时前
基于Spring Boot的企业网盘的设计与实现(毕业论文)
java·spring boot·vue·毕业设计·论文·毕业论文·企业网盘的设计与实现
Hx_Ma163 小时前
SSM搭建(三)Spring整合SpringMVC框架
java·后端·spring
无风听海4 小时前
.NET10之ASP.NET Core的Filter管线
java·asp.net·.net