LeetCode 供暖器

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

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

示例 1:

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

示例 2:

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

**思路分析:**先将两个数组进行升序排序,如果某个房屋出现在两个暖器的中间,则取一个半径的较小值。

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;
	}
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/88969910