供暖 heaters
给出位于同一个水平线上的房屋houses和供暖器heaters的位置。要求设计一个具有最小加热半径的供暖器可以向所有房屋供暖
houses = [1,2,3], heaters = 【2】
1
houses = [1,2,3,4], heaters = [1,4]
1
思路
因为每个heater的加热半径是一样的,所以求出每一个house到距离它最近的heater的距离,然后在这个距离中找到最大的那个,就可以满足我们的目标。
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int ans = 0;
for (int i = 0; i < houses.length ; i++) {
int x = houses[i];
int j = binarysearch01(heaters,x);
// left present the distance between houses[i] and the first heater index bigger than houses[i],
// if not exist the first bigger element ,
// left present the distance between houses[i] and the last heater index small than houses[i] .
int left =Math.abs(x-heaters[j]);
// right present the distance between house[i] and the former heater.
// when j equal zero,heater[j-1] is illegal.So choose the bigger one.
ans = Math.max(ans,Math.min(left,right));
}
return ans;
}
// find index of the first element bigger than x
// if exists return index, OR finally return the last index of element that smaller than x.
public int binarysearch01(int[] arr ,int x){
int head =0;
int tail = arr.length-1;
int mid =0;
while (head<tail){
mid = (head+tail)>>1;
if (arr[mid]>=x){
tail = mid;
}
else{
head = mid+1;
}
}
return head;
}
Tag
binary search