首页 > 代码库 > 475. Heaters

475. Heaters

http://www.cnblogs.com/EdwardLiu/p/6197086.html

https://leetcode.com/problems/heaters/#/description

 

public int findRadius(int[] houses, int[] heaters) {
if (houses == null || houses.length == 0) {
return 0;
}
Arrays.sort(houses);
Arrays.sort(heaters);
int res = 0, j = 0;
for (int i = 0; i < houses.length; i++) {
while (j + 1 < heaters.length && Math.abs(houses[i] - heaters[j]) >= Math.abs(houses[i] - heaters[j + 1])) {
j++;
}
res = Math.max(res, Math.abs(houses[i] - heaters[j]));

}
return res;
}

 

 

二分查找法:

public class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int result = Integer.MIN_VALUE;

for (int house : houses) {
int index = Arrays.binarySearch(heaters, house); // if put each house in heaters array, this is each house‘s insertion position
if (index < 0) {
index = -(index + 1);
}
int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE; //this house‘s distance with heaters infront of it, maybe none in front
int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE; //this house‘s distance with heaters after it

result = Math.max(result, Math.min(dist1, dist2));
}

return result;
}
}

475. Heaters