思路: 1、先按照面積計(jì)算每個(gè)rectangle的權(quán)重 2、根據(jù)權(quán)重選擇rectangle的下標(biāo)(參考 528. Random Pick with Weight) 3、選好rectangle后,根據(jù)范圍隨機(jī)生成橫坐標(biāo)x、縱坐標(biāo)y
classSolution{Random r;intN;int[][] rects;long[] weight;// 權(quán)重long[] weightSum;// 權(quán)重前綴和publicSolution(int[][] rects){this.rects = rects;r =newRandom();N= rects.length;weight =newlong[N];weightSum =newlong[N];for(int i =0; i <N; i++){weight[i]=((long) rects[i][2]+1- rects[i][0])*((long) rects[i][3]+1- rects[i][1]);// +1 因?yàn)榘吔?#xff01;坑!!}weightSum[0]=0;if(N>1) weightSum[1]= weight[0];for(int i =2; i <N; i++){weightSum[i]= weightSum[i -1]+ weight[i -1];}}publicint[]pick(){// 根據(jù)權(quán)重選擇一個(gè)rectanglelong sum = weight[N-1]+ weightSum[N-1];long rand =randLong(0, sum);// 反向查找randLong屬于的indexintL=0;intR=N-1;int index =-1;if(weightSum[N-1]<= rand){index =N-1;}else{while(L<R){intM=L+(R-L)/2;if(weightSum[M]== rand){index =M;break;}elseif(weightSum[M]< rand){if(L==M){index =M;break;}L=M;}else{R=M-1;if(weightSum[R]<= rand){index =R;break;}}}if(index ==-1) index =L;}int[] rec = rects[index];long x =randLong(rec[0], rec[2]+1);long y =randLong(rec[1], rec[3]+1);returnnewint[]{(int) x,(int) y};}publiclongrandLong(long a,long b){// 左閉右開(kāi)return a +(long)(Math.random()*(b - a));}}/*** Your Solution object will be instantiated and called as such:* Solution obj = new Solution(rects);* int[] param_1 = obj.pick();*/