LeetCode解题分享:475. Heaters

Problem

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.

解题思路

   简单来说,就是给定锅炉的位置,计算可以覆盖全部房屋的最小的锅炉半径。此时,我们需要考虑一个问题,我们的房屋的位置确定下来了,那么我们的房屋所对应的锅炉应该在哪里?很显然,对应锅炉的位置应该是从房屋出发,向左走或者向右走第一个碰见的那个锅炉,也就是说左边或者右边最接近的那个锅炉才应该对应我们的房屋。如果我们对应的房屋的地址门口正好有一个锅炉,那么我们就不用向左向右去找了。所以,很显然,我们第一步需要对所有的房屋和锅炉的位置按照从小到大的顺序进行排序,然后用二分查找的方法对每一个房屋所对应的锅炉进行查找。考虑到C++中直接对二分查找进行了封装,此处我们选择 u p p e r _ b o u n d upper\_bound upper_bound函数查找第一个等于或者大于当前房屋的位置的锅炉。当我们查找到了每一个房屋所对应的最接近的那个锅炉之后,为了进行全部的覆盖,我们要取所有的房屋到最近的锅炉的距离的最大值。

   代码如下:

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) 
    {
		sort(houses.begin(), houses.end());
		sort(heaters.begin(), heaters.end());

		int dis = 0;

		for (int& h : houses)
		{
			auto p = upper_bound(heaters.begin(), heaters.end(), h);
			if (p == heaters.end())
			{
				dis = std::max(dis, std::abs(h - *(p - 1)));
				continue;
			}

			if (p == heaters.begin())
			{
				dis = std::max(dis, std::abs(h - *p));
				continue;
			}

			int temp = std::min(std::abs(h - *p), std::abs(h - *(p - 1)));
			dis = std::max(dis, temp);
		}
		return dis;


	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值