475. Heaters

#### QUESTION:

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 are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
3. As long as a house is in the heaters’ warm radius range, it can be warmed.

Example 1:

``````Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

``````

Example 2:

``````Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
``````

#### EXPLANATION:

1.找到距离房子最近的供热点（二分法进行查找），并计算出最短半径。

2.求出所有最短半径的最大值就是最后的答案。

#### SOLUTION:

``````public class Solution {
public int findRadius(int[] houses, int[] heaters) {
int result = -1;
Arrays.sort(heaters);
for(int i = 0;i<houses.length;i++){
int house = houses[i];
search = Math.abs(heaters[search] - houses[i]);
result = Math.max(result,search);
}
return result;
}
int low = 0,high = heaters.length-1;

while (low<=high){
int mid = (low + high) >>> 1;
int midVal = heaters[mid];

if (midVal < key){
low = mid + 1;
}else if (midVal > key){
high = mid - 1;
}else
return mid; // key found
}
low = low>heaters.length-1?heaters.length-1:low;
high = high<0?0:high;
return Math.abs(key-heaters[low])-Math.abs(heaters[high]-key)>0?high:low;
}
}

//更为优雅的方式：
public class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int i = 0, res = 0;
for(int house : houses){
while(i < heaters.length - 1 && 2 * house >= heaters[i] + heaters[i + 1]) i++;
res = Math.max(res, Math.abs(heaters[i] - house));
}
return res;
}
}
``````
>