You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: leetcode/binary-search/497-random-point-in-non-overlapping-rectangles.md
+11-11Lines changed: 11 additions & 11 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@
4
4
5
5
Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles.
6
6
7
-
**Note:
7
+
**Note:
8
8
**
9
9
10
10
1. An integer point is a point that has integer coordinates.
@@ -42,14 +42,14 @@ The input is two lists: the subroutines called and their arguments. Solution's c
42
42
### Thought Process {#thought-process}
43
43
44
44
1. Binary Search
45
-
1.Since the rectangles are non-overlapping, we can use each rectangle's area divided by total as probability of being picked
46
-
2.Unfortunately some rectangles have zero area, therefore we need to use count of points instead
47
-
3.In the process of counting, we accumulated the count and save it to presum array
48
-
4.After generating r in the range of \[0, totalCount\), we use it to find out which rectangle is picked through process of binary search through presum array
49
-
50
-
1. After locating the rectangle, we can either generate
51
-
2. Time complexity O\(n\), where n is number of rectangles
52
-
3. Space complexity O\(n\)
45
+
1.To get a random point, we have to locate one rectangle then pick from it
46
+
2.Initial thought using area fails due to some rectangles have area of 0, we use count of points instead
47
+
3.As we count through each rectangles, we accumulate the count in presum array and record total counts
48
+
4.Then we generate a number, r, in \[0, totalCount\), we perform binary search to locate the rectangle that contains it \(using number in \[1, totalCount\] will keep binary search traditional\)
49
+
5. After locating the rectangle, we can either generate a point in x plus a point in y or use r generated above to get the final result
50
+
6. The second way avoid extra random point generation, and the formula is x = x0 + \(r % c\), and y = y0 + \(r / c\) where r is reset to zero-based and rectangle-based by r - presum\[prev\] + 1 and c points count
51
+
7. Time complexity O\(n\)
52
+
8. Space complexity O\(n\)
53
53
2. asd
54
54
55
55
### Solution
@@ -71,11 +71,11 @@ class Solution {
71
71
a[i] = totalArea;
72
72
}
73
73
}
74
-
74
+
75
75
privateintgetArea(int[] rect) {
76
76
return (rect[2] - rect[0]) * (rect[3] - rect[1]);
77
77
}
78
-
78
+
79
79
publicint[] pick() {
80
80
int i = binarySearch(a, rand.nextInt(totalArea) +1);
81
81
int x = rand.nextInt(rects[i][2] - rects[i][0] +1) + rects[i][0];
0 commit comments