475. Heaters

Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.

Every house can be warmed, as long as the house is within the heater's warm radius range. 

Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.

Notice that all the heaters follow your radius standard, and the warm radius will the same.

Example 1:

Input: houses = [1,2,3], heaters = [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: houses = [1,2,3,4], heaters = [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.

Example 3:

Input: houses = [1,5], heaters = [2]
Output: 3

Constraints:

  • 1 <= houses.length, heaters.length <= 3 * 104
  • 1 <= houses[i], heaters[i] <= 109

题目:给两个数组,一个代表房子位置,一个代表heater位置。都在一条直线上,求使得heater能把所有房屋都照顾到的最小辐射距离。

思路:先将两个数组排序,双指针。房子i挨个遍历,heaters j可以漏掉一些。每次先移动j指针,找到houses[i]前面离houses[i]最近的heater。也就是说houses[i]要在heaters[j]和heaters[j+1]之间。此时可以判断heaters[j]还是heaters[j+1]能照顾到它,哪个离它距离最近就归哪个管。更新辐射值。边界情况,如果houses[0]在heaters[0]之前,即houses[i] <= heaters[j]则必须归 heaters[0]照顾,或是houses[i]在最后一个heaters.back()之后,则必须归heaters.back()照顾。每次都更新辐射值。

代码:

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        int res = 0, i = 0, j = 0;
        while(i < houses.size()){
            while(j < heaters.size()-1 && heaters[j+1] <= houses[i]){
                j++;
            }
            if(houses[i] <= heaters[j]){
                res = max(res, heaters[j] - houses[i]);
                i++;
            } else {
                if(heaters[j]+res >= houses[i]) i++;
                else if(j == heaters.size()-1){
                    return max(res, (houses.back() - heaters.back()));
                } else {
                    if(heaters[j+1] - res <= houses[i]) i++;
                    else {
                        res = max(res, min(houses[i]-heaters[j], heaters[j+1]-houses[i]));
                        i++;
                    }
                }
            }
        }
        return res;
    }
};

time: O(NlogN), space: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值