Leetcode475.Heaters供暖器

冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。

现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。

所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。

说明:

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

示例 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 len1 = houses.size();
        int len2 = heaters.size();
        int res = 0;
        int cnt = 0;//设定一个标记,标记为位置比目前第i个房屋小的供暖器,优化,不然会超时
        for(int i = 0; i < len1; i++)
        {
            int temp = abs(houses[i] - heaters[cnt]);
            for(int j = cnt + 1; j < len2; j++)
            {
                if(houses[i] == heaters[j])
                {
                    temp = 0;
                    break;
                }
                else if(houses[i] < heaters[j])
                {
                    temp = min(temp, heaters[j] - houses[i]);
                }
                else
                {
                    temp = min(temp, houses[i] - heaters[j]);
                    cnt = j;
                }
            }
            res = max(temp, res);
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/lMonster81/p/10434075.html