TreeMap<Integer, Integer> map;
public Solution(int[][] rects) {
for (int i = 0; i < rects.length; i++) {
// 坐标是从0开始,所以计算面积时,边长都要相应加1
totalArea += (rect[2] - rect[0] + 1) *(rect[3] - rect[1] + 1);
// rand.nextInt(totalArea) 会返回(0, totalArea - 1)的随机数,所以rand.nextInt(totalArea) + 1保证
// 随机生成数在[1, totalArea]之间
int key = map.ceilingKey(rand.nextInt(totalArea) + 1);
return pickPointInRect(rects[map.get(key)]);
public int[] pickPointInRect(int[] rect) {
int x = rect[0] + rand.nextInt(rect[2] - rect[0] + 1);
int y = rect[1] + rand.nextInt(rect[3] - rect[1] + 1);
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(rects);
* int[] param_1 = obj.pick();