classSolution:def__init__(self,w:List[int]):n=len(w)self.presum=[0]*(n+1)foriinrange(n):self.presum[i+1]=self.presum[i]+w[i]defpickIndex(self)->int:n=len(self.presum)x=random.randint(1,self.presum[-1])left,right=0,n-2whileleft<right:mid=(left+right)>>1ifself.presum[mid+1]>=x:right=midelse:left=mid+1returnleft# Your Solution object will be instantiated and called as such:# obj = Solution(w)# param_1 = obj.pickIndex()
classSolution{privateint[]presum;publicSolution(int[]w){intn=w.length;presum=newint[n+1];for(inti=0;i<n;++i){presum[i+1]=presum[i]+w[i];}}publicintpickIndex(){intn=presum.length;intx=(int)(Math.random()*presum[n-1])+1;intleft=0,right=n-2;while(left<right){intmid=(left+right)>>1;if(presum[mid+1]>=x){right=mid;}else{left=mid+1;}}returnleft;}}/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(w); * int param_1 = obj.pickIndex(); */
classSolution{public:vector<int>presum;Solution(vector<int>&w){intn=w.size();presum.resize(n+1);for(inti=0;i<n;++i)presum[i+1]=presum[i]+w[i];}intpickIndex(){intn=presum.size();intx=rand()%presum[n-1]+1;intleft=0,right=n-2;while(left<right){intmid=left+right>>1;if(presum[mid+1]>=x)right=mid;elseleft=mid+1;}returnleft;}};/** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(w); * int param_1 = obj->pickIndex(); */
typeSolutionstruct{presum[]int}funcConstructor(w[]int)Solution{n:=len(w)pre:=make([]int,n+1)fori:=0;i<n;i++{pre[i+1]=pre[i]+w[i]}returnSolution{pre}}func(this*Solution)PickIndex()int{n:=len(this.presum)x:=rand.Intn(this.presum[n-1])+1left,right:=0,n-2forleft<right{mid:=(left+right)>>1ifthis.presum[mid+1]>=x{right=mid}else{left=mid+1}}returnleft}/** * Your Solution object will be instantiated and called as such: * obj := Constructor(w); * param_1 := obj.PickIndex(); */
classSolution{privatevarpresum:[Int]init(_w:[Int]){letn=w.countpresum=[Int](repeating:0,count:n+1)foriin0..<n{presum[i+1]=presum[i]+w[i]}}funcpickIndex()->Int{letn=presum.countletx=Int.random(in:1...presum[n-1])varleft=0varright=n-2whileleft<right{letmid=(left+right)>>1ifpresum[mid+1]>=x{right=mid}else{left=mid+1}}returnleft}}/** * Your Solution object will be instantiated and called as such: * let w = [1] * let solution = Solution(w) * solution.pickIndex() */