冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。
所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。
说明:

给出的房屋和供暖器的数目是非负数且不会超过 25000。
给出的房屋和供暖器的位置均是非负数且不会超过10^9。
只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
所有供暖器都遵循你的半径标准,加热的半径也一样。

示例 1:

输入: [1,2,3],[2]
输出: 1
解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。

示例 2:

输入: [1,2,3,4],[1,4]
输出: 1
解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。

思路分析: 先将两个数组进行升序排序,分五种情况进行处理不同的处理。
LeetCode 供暖器

class Solution {
public:
	int findRadius(vector<int>& houses, vector<int>& heaters) {
		sort(houses.begin(), houses.end());//升序排序
		sort(heaters.begin(), heaters.end());
		int housesSize = houses.size(), heatersSize = heaters.size();
		int heatersIndex = 0, minRes = 0;//当前供暖器的下标,最小半径
        //扫描所有房屋
		for (int index = 0; index < housesSize; ++index) {
		//每次只会处理当前已有半径无法覆盖的房屋
			if (houses[index] < heaters[heatersIndex] - minRes) {
                //第一种:房屋出现在供暖器的左边,只能直接更新半径
				minRes = heaters[heatersIndex] - houses[index];
			}
			else if (houses[index] > heaters[heatersIndex] + minRes) {
				if (heatersIndex + 1 < heatersSize) {
				//房屋出现在两个供暖器的中间
					if (heaters[heatersIndex + 1] <= houses[index]) {
                        //第四种情况:当前供暖器不是离当前房屋最近的供暖器
						heatersIndex += 1;//更新供暖器下标
						index -= 1;//由于这个房屋还未得到处理,需要重新处理(但是在最外层的for循环会自增,所以需要回退)
						continue;
					}
					if (heaters[heatersIndex + 1] - minRes <= houses[index]) {
                        //第二种情况:当下一个供暖器能够供暖这个房屋,直接更新即可
						heatersIndex += 1;
					}
					else if (heaters[heatersIndex + 1] - houses[index] <= houses[index] - heaters[heatersIndex]) {
                        //第三种情况:下一个供暖器供暖此房屋需要的半径小于当前供暖器所需要的半径
						heatersIndex += 1;
						minRes = heaters[heatersIndex] - houses[index];
					}
					else {
                        //第三种:最后只能直接更新半径了
						minRes = houses[index] - heaters[heatersIndex];
					}
				}
				else {
                    //第五种:最后只能直接更新半径了
					minRes = houses[index] - heaters[heatersIndex];
				}
			}
		}
		return minRes;
	}
};

LeetCode 供暖器

相关文章:

  • 2021-12-14
  • 2021-08-21
  • 2021-12-31
  • 2021-09-13
  • 2022-12-23
  • 2021-04-10
  • 2021-08-01
  • 2021-12-29
猜你喜欢
  • 2021-07-29
  • 2022-12-23
  • 2021-11-24
  • 2021-10-19
  • 2021-12-24
  • 2021-11-17
  • 2021-11-06
相关资源
相似解决方案