1. 程式人生 > >528. Random Pick with Weight

528. Random Pick with Weight

pic turn int return arrays solution arc class 初始

每個位置都是邊界 二分法找

 1 class Solution {
 2     Random random = new Random(); //記得初始化
 3     int[] arr;
 4 
 5     public Solution(int[] w) {
 6         arr = new int[w.length];
 7         arr[0] = w[0];
 8         for(int i = 1; i < w.length; i++){
 9             arr[i] = arr[i-1] + w[i];
10         }
11 12 } 13 14 public int pickIndex() { 15 // System.out.println(arr[0]); 16 int num = random.nextInt(arr[arr.length - 1]) + 1; 17 int index = Arrays.binarySearch(arr, num); 18 if(index < 0){ 19 index = -(index+1); 20 } 21 return
index; 22 23 } 24 }

528. Random Pick with Weight