//

给定一个由非重叠的轴对齐矩形的数组 rects ,其中 rects[i] = [ai, bi, xi, yi] 表示 (ai, bi) 是第 i 个矩形的左下角点,(xi, yi) 是第 i 个矩形的右上角点。设计一个算法来随机挑选一个被某一矩形覆盖的整数点。矩形周长上的点也算做是被矩形覆盖。所有满足要求的点必须等概率被返回。

// //

在给定的矩形覆盖的空间内的任何整数点都有可能被返回。

// //

请注意 ,整数点是具有整数坐标的点。

// //

实现 Solution 类:

// // // //
    //
// //

 

// //

示例 1:

// //

// //
//输入: 
//["Solution", "pick", "pick", "pick", "pick", "pick"]
//[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
//输出: 
//[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]
//
//解释:
//Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
//solution.pick(); // 返回 [1, -2]
//solution.pick(); // 返回 [1, -1]
//solution.pick(); // 返回 [-1, -2]
//solution.pick(); // 返回 [-2, -2]
//solution.pick(); // 返回 [0, 0]
// //

 

// //

提示:

// // //
Related Topics
  • 水塘抽样
  • 数学
  • 二分查找
  • 有序集合
  • 前缀和
  • 随机化

  • 👍 98
  • 👎 0
  • package leetcode.editor.cn; import java.util.Random; // 497:非重叠矩形中的随机点 public class RandomPointInNonOverlappingRectangles { public static void main(String[] args) { // TO TEST } //leetcode submit region begin(Prohibit modification and deletion) class Solution { int[][] rects; int[] mul; int count; Random random = new Random(); public Solution(int[][] rects) { this.rects = rects; count = this.rects.length; mul = new int[count + 1]; for (int i = 1; i <= count; i++) { mul[i] = mul[i - 1] + (this.rects[i - 1][2] - this.rects[i - 1][0] + 1) * (this.rects[i - 1][3] - this.rects[i - 1][1] + 1); } } public int[] pick() { int index = random.nextInt(mul[count]) + 1; int left = 0; int right = count; while (left < right) { int mid = left + right >> 1; if (mul[mid] >= index) { right = mid; } else { left = mid + 1; } } return new int[]{ random.nextInt(rects[right - 1][2] - rects[right - 1][0] + 1) + rects[right - 1][0], random.nextInt(rects[right - 1][3] - rects[right - 1][1] + 1) + rects[right - 1][1] }; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(rects); * int[] param_1 = obj.pick(); */ //leetcode submit region end(Prohibit modification and deletion) }