首页 > 其他 > 详细

475. Heaters

时间:2017-06-20 22:11:57      阅读:417      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/apanda009/p/7056326.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!