497. Random Point in Non-overlapping Rectangles

这题就是把矩形的面积加起来,
对总面积做求一个random数量
然后做binary search,找出在哪个矩形里面。
然后再去矩形里找到底是哪个点。
注意算面积的时候要 对长宽各加1。
binarySearch的时候要找大于它的最小值。
除此之外没什么

class Solution {
    int[] areas;
    int[][] rects;
    Random random;
    public Solution(int[][] rects) {
        this.rects = rects;
        this.areas = new int[rects.length];
        for (int i = 0; i < rects.length; i++) {
            areas[i] = getArea(rects[i]) + (i > 0 ? areas[i - 1] : 0); //忘了加了 
        }
        random = new Random();
    }
    
    public int[] pick() {
        int num = random.nextInt(areas[areas.length - 1]);
        int index = myBinarySearch(areas, num);
        if (index != 0) {
            num -= areas[index - 1];
        }
        return findKth(rects[index], num);
    }
    private int[] findKth(int[] rect, int num) {
        int pointEachRow = rect[2] - rect[0] + 1;
        int ansX = rect[0] + (num % pointEachRow);
        int ansY = rect[1] + (num / pointEachRow);
        return new int[]{ansX, ansY};
    }
    
    private int myBinarySearch(int[] areas, int num) {
        //find the smallest larger >;
        int l = 0, r = areas.length - 1;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (areas[mid] <= num) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return l;
    }
    
    private int getArea(int[] rect) {
        return (rect[2] - rect[0] + 1 ) * (rect[3] - rect[1] + 1);
    }
}

你可能感兴趣的:(497. Random Point in Non-overlapping Rectangles)