[LeetCode] Heaters

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 ho

设计一个固定半径的加热器,以温暖所有房屋。在一个水平线上安置加热器,找出加热器最小半径,以便所有房屋可以被加热器覆盖。

给定两个数组,一个数组houses表示房屋的位置。一个数组heaters表示加热器的位置。数组值分别表示水平线上的位置坐标。

首先先对两个数组进行排序,再设置两个数组分别计算加热器距离与房屋的距离,lhs表示加热器左边的房屋与加热器的距离(需要正向遍历houses与heaters),rhs表示加热器右边的房屋与加热器的距离(需要逆向遍历houses与heaters)。 

然后找出lhs与rhs数组中对应位置的最小值以及这些最小值中的最大值。这个最大值就是题目要求的加热器半径。

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        int radius = 0;
        if (heaters.empty())
            return radius;
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        vector<int> lhs(houses.size(), INT_MAX);
        vector<int> rhs(houses.size(), INT_MAX);
        for (int i = 0, j = 0; i < houses.size() && j < heaters.size();) {
            if (houses[i] <= heaters[j]) {
                lhs[i] = heaters[j] - houses[i];
                i++;
            }
            else {
                j++;
            }
        }
        for (int i = houses.size() - 1, j = heaters.size() - 1; i >= 0 && j >= 0;) {
            if (houses[i] >= heaters[j]) {
                rhs[i] = houses[i] - heaters[j];
                i--;
            }
            else {
                j--;
            }
        }
        for (int i = 0; i < houses.size(); i++) {
            int tmp = min(lhs[i], rhs[i]);
            radius = max(radius, tmp);
        }
        return radius;
    }
};
// 75 ms
原文地址:https://www.cnblogs.com/immjc/p/7998436.html