Leetcode-475. Heaters

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

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters' warm radius range, it can be warmed.
  4. 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;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值