码迷,mamicode.com
首页 > 其他好文 > 详细

475. Heaters

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

标签:this   return   strong   res   use   rdl   com   turn   for   

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

标签:this   return   strong   res   use   rdl   com   turn   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!