Last active
April 8, 2019 06:17
-
-
Save azimbabu/3727f971e162c89900de4668d9e432b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
private int[][] ranges; | |
private int totalSum; | |
private Random random; | |
public Solution(int[] weights) { | |
ranges = new int[weights.length][2]; | |
for (int i=0, current = 0; i < weights.length; i++) { | |
ranges[i] = new int[]{current, current + weights[i]}; | |
current = current + weights[i]; | |
totalSum += weights[i]; | |
} | |
random = new Random(); | |
} | |
public int pickIndex() { | |
int randomNumber = random.nextInt(totalSum); | |
int left = 0, right = ranges.length-1; | |
while (left <= right) { | |
int mid = left + (right - left)/2; | |
int[] range = ranges[mid]; | |
if (range[0] <= randomNumber && randomNumber < range[1]) { | |
return mid; | |
} else if (randomNumber < range[0]) { | |
right = mid - 1; | |
} else { | |
left = mid + 1; | |
} | |
} | |
throw new AssertionError("Should not reach here"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment