week3

Heaters(from leetcode

题意:

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.


分析:

这道题的思路比较容易想出来,从第一个加热器开始算,第一个加热器肯定要加热前面所有的房子,以此得出一个半径,这个半径同样对后面的房子管用。然后再看半径外的下一个加速器,以此类推即可。

但是比较坑的地方在于,首先房子的序列并不是一个连续的序列,这一点也是我提交之后才发现的。两个例子虽然给的是连续,但实际里面会有[1,5]等序列。于是我打算用一个连续的序列来代替原来的序列。然后发现直接run time error了。。。显然也不是这么做的。于是我又加以修改之后感觉完全ok了,但是又发现自己没有考虑最后一个热水器需要加热后面所有的房子。然后我又对这一点加以修改,然后我又发现热水器还能放在最后一个房子后面。。。

然后我发现我之前想的代码思路完全不好使了,只能参考大佬的代码利用abs函数重新写了一个。

主要的问题还是在于我是尽可能去找r中较大的一个,而不是先选一个较大的然后去找较小的


代码:

class Solution {
public:
   int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(houses.begin(),houses.end());
        sort(heaters.begin(),heaters.end());
        int x = 1,r = 0;
        for(int i = 0; i < houses.size(); i++)
        {
            int t=abs(heaters[x-1]-houses[i]);
            for(int j=x; j<heaters.size(); j++)
            {
                if(abs(heaters[j]-houses[i])<=t)
                {
                    t=abs(heaters[j]-houses[i]);
                    x=j+1;
                   
                }
                else
                    break;
            }
            r=max(r,t);
        }
        return r;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值