您的位置:首页 > 编程语言 > Java开发

Leetcode-475. Heaters

2017-01-01 19:14 357 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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:

Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
As long as a house is in the heaters' warm radius range, it can be warmed.
All the heaters follow your radius standard and the warm radius will the same.

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.

这个题目先排序,这样房子和加热器的位置就是有序的,接下来每次找到两个加热器,一个房子,分三种情况:

1、初始状态,房子可能在两个加热器的左边,那么取离他最近的加热器的距离。
2、迭代过程中,找两个加热器离房子最近,且房子在两个加热器中间,取离房子最近的加热器的距离。

3、最后迭代房子可能在两个加热器的右边,那么取离他最近的加热器的距离。

迭代完毕,如果加热器有剩余,不用管,如果房子有剩余,让房子与最后一个加热器相减即可。Your runtime beats 83.30% of java submissions

public class Solution {
public int findRadius(int[] houses, int[] heaters) {
if(houses.length == 0) return 0;
if(heaters.length == 0)return Integer.MAX_VALUE;
Arrays.sort(houses);
Arrays.sort(heaters);
int miniRadius = 0;
int i = 0, j = 0;
int prePosition = heaters[0];
while( i < houses.length && j < heaters.length){
if(houses[i] > heaters [j]){
prePosition = heaters [j];
j ++;
}
else if(heaters[j] >= houses[i]){
int distance_pre = Math.abs(houses[i] - prePosition), distance_next = Math.abs(heaters[j] - houses[i]);
int current_min = Math.min(distance_next,distance_pre);
miniRadius = Math.max(miniRadius,current_min);
i++;
}
}
while(i < houses.length){
int distance = houses[i] - heaters[j-1];
miniRadius = Math.max(miniRadius,distance);
i++;
}
return miniRadius;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法