528. Random Pick with Weight
Explanation
To solve this problem, we need to generate a random index based on the weights provided in the input array. We can achieve this by creating a prefix sum array to store the cumulative sum of weights. We then generate a random number between 1 and the total sum of weights, and find the index where this random number falls in the prefix sum array.
import java.util.Random;
class Solution {
int[] prefixSum;
Random rand;
public Solution(int[] w) {
prefixSum = new int[w.length];
rand = new Random();
prefixSum[0] = w[0];
for (int i = 1; i < w.length; i++) {
prefixSum[i] = prefixSum[i - 1] + w[i];
}
}
public int pickIndex() {
int totalSum = prefixSum[prefixSum.length - 1];
int randNum = rand.nextInt(totalSum) + 1;
int left = 0, right = prefixSum.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (prefixSum[mid] < randNum) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.