[LeetCode] 475. Heaters

42 篇文章 0 订阅
37 篇文章 0 订阅

题目链接: https://leetcode.com/problems/heaters/description/

Description

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 houses can be warmed.

解题思路

题意大致为,在一条水平线上有若干房间和加热器,给定房间和加热器的坐标,求加热器所需的最小供暖范围,使得所有房间有加热器为其供暖。

主要思路为对每一个房间,寻找离他最近的加热器,统计这些房间与离他最近的加热器的距离,在这些距离中取最大值即为所求。

具体实现的话,首先对加热器的位置进行排序,按照从小到大的顺序。然后对每一个房间,在加热器数组中用二分查找算法找到离他最近的加热器的位置,计算距离并更新目标半径。

另外,我用的二分查找为”在数组中找到最后一个小于等于目标值的下标,若不存在则返回-1“,因此除了二分查找得到的下标 index 对应的加热器与该房间距离,还要比较下标为 index + 1 的加热器与房间的距离,取两者之间较小值。

Code

class Solution {
public:
    int findRadius(vector<int> &houses, vector<int> &heaters) {
        sort(heaters.begin(), heaters.end());

        int radius = 0;

        for (int i = 0; i < houses.size(); ++i) {
            int lli = max(0, last_le_val(heaters, houses[i]));
            int lli_dist = abs(heaters[lli] - houses[i]);
            int after_lli_dist = lli + 1 < heaters.size() ?
                abs(heaters[lli + 1] - houses[i]) : INT32_MAX;                
            radius = max(radius, min(lli_dist, after_lli_dist));
        }

        return radius;
    }

    int last_le_val(vector<int> &heaters, int val) {
        int mid, left = 0, right = heaters.size() - 1;

        while (left <= right) {
            mid = (left + right) >> 1;
            if (heaters[mid] > val) right = mid - 1;
            else left = mid + 1;
        }

        return right;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值