Winter is coming!Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you is given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so it all HO Uses could is covered by those heaters. So, your input would be the positions of houses and heaters seperately, and your expected output would be the minimum radius Standard of heaters. Note:numbers of houses and heaters You is given are non-negative and would not exceed 25000. Positions of houses and heaters You is given are non-negative and would not exceed 10^9. asLongAs a house was in the heaters ' warm radius range, it can be warmed.All the heaters follow your radius and the warm radius would the same. Example1: Input: [1,2,3],[2]output:1explanation:the only heater is placed in the position2, andifWe use the radius 1The houses can be warmed. Example2: Input: [1,2,3,4],[1,4]output:1explanation:the heater is placed in the position1 and 4. We need to use RADIUS 1 standard and then all the houses can is warmed.
Solution:why we use binary search here, THR brute force search method is get max (min (Dist)), to reduce time Complexi Xity we need to use binary search (why), there is elments (in heaters) close to the houses[i]
Here binary search model was to find first >= target. (Basic model is search insert poition)
classSolution {//check houses, compare Maxdist (min (house[i], heaters[j]): min distance between house[i], heaters[j]; and get max of them; Max (min (dist)) Public intFindradius (int[] houses,int[] heaters) { intRadius = 0;//MaxArrays.sort (heaters); for(inti = 0; i){ intMin =Integer.max_value; //binary search (find first >= houses), Target is houses[i] intL = 0, r = heaters.length-1; while(L <=R) { intm = (r-l)/2 +l; if(Heaters[m] >= houses[i]) R = m-1 ; ElseL = m+1; } //System.out.println (L); //l was the index, could be 0, >=heaters.length intD1 = l-1>=0? (Houses[i]-heaters[l-1]): Integer.max_value; intD2 = L//handle all the thingsmin = d1<d2?d1:d2; if(min > Radius) radius =min; } returnradius; }}
Another way:call built in function of binary search in the Arrays.binarysearch (); (Https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch (int[],%20int)) https:// WWW.GEEKSFORGEEKS.ORG/ARRAYS-BINARYSEARCH-JAVA-EXAMPLES-SET-1/(Geekforgeek)
Public classSolution { Public intFindradius (int[] houses,int[] heaters) {Arrays.sort (heaters); intresult =Integer.min_value; for(inthouse:houses) { intindex =Arrays.binarysearch (heaters, House); if(Index < 0) {Index=-(index + 1); } intDist1 = index-1 >= 0? House-heaters[index-1]: integer.max_value; intDist2 = Index < heaters.length? Heaters[index]-House:Integer.MAX_VALUE; Result=Math.max (Result, Math.min (Dist1, dist2)); } returnresult; }}
Lastly, remember to sort first
475. Heaters (Start binary search, appplication for binary search)