Skip to content

Commit a26eb08

Browse files
update 528
1 parent d0edd44 commit a26eb08

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_528.java

+20-8
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,40 @@
44

55
public class _528 {
66
public static class Solution1 {
7+
/**
8+
* Credit: https://leetcode.com/problems/random-pick-with-weight/editorial/
9+
* <p>
10+
* Mental gymnastics (which is explained step by step in the above link):
11+
* 1. picture this to be a ball throwing onto a line from the starting point (0,0);
12+
* 2. where this ball is going to land on the line is a probability problem, i.e. an offset to the starting point (0,0);
13+
* 3. we can use prefix sums array to simulate this line (each value in the array is positive as it represents the weight/probability of it being picked, so cannot be zero or negative);
14+
* 4. we can use Random() to generate a random number called index bounded by the last value of the prefix sums array, i.e. the biggest offset possible;
15+
* 5. then we can use binary search to find where this random number: index, would fit in the prefix sums array.
16+
*/
717
Random random;
8-
int[] preSums;
18+
int[] prefixSums;
919

1020
public Solution1(int[] w) {
1121
this.random = new Random();
12-
for (int i = 1; i < w.length; ++i) {
13-
w[i] += w[i - 1];
22+
this.prefixSums = new int[w.length];
23+
int prefixSum = 0;
24+
for (int i = 0; i < w.length; ++i) {
25+
prefixSum += w[i];
26+
prefixSums[i] = prefixSum;
1427
}
15-
this.preSums = w;
1628
}
1729

1830
public int pickIndex() {
19-
int len = preSums.length;
20-
int idx = random.nextInt(preSums[len - 1]) + 1;
31+
int len = prefixSums.length;
32+
int idx = random.nextInt(prefixSums[len - 1]) + 1;
2133
int left = 0;
2234
int right = len - 1;
2335
// search position
2436
while (left < right) {
2537
int mid = left + (right - left) / 2;
26-
if (preSums[mid] == idx) {
38+
if (prefixSums[mid] == idx) {
2739
return mid;
28-
} else if (preSums[mid] < idx) {
40+
} else if (prefixSums[mid] < idx) {
2941
left = mid + 1;
3042
} else {
3143
right = mid;

Diff for: src/test/java/com/fishercoder/_528Test.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
package com.fishercoder;
22

33
import com.fishercoder.solutions._528;
4-
import org.junit.Test;
4+
import org.junit.jupiter.api.Test;
55

6-
import static org.junit.Assert.assertEquals;
6+
import static org.junit.jupiter.api.Assertions.assertEquals;
77

88
public class _528Test {
99
private static _528.Solution1 solution1;

0 commit comments

Comments
 (0)