LeetCode_Dec_3rd_Week

December 20th : 475. 供暖器
December 21st : 1154. 一年中的第几天


December 20th : 475. 供暖器

对于每个房屋,要么用前面的暖气,要么用后面的,二者取近的,得到距离;对于所有的房屋,选择最大的上述距离。

这里需要注意的是,对于某个房屋,它只有前面或者是只有后边有暖气,这种情况需要考虑到。

在对边界值进行查找的过程中,常用到二分查找(对于边界的二分,直观看是对有序序列进行对半划分),这里stl algorithm中的upper_boundlower_bound很好用,具体的函数签名如下:

lower_bound对应求得的是第一个不小于value的值所对应的迭代器,也即是大于等于区间的左边界,这样称为lower bound就不难理解了。

同理,upper_bound求得的是不大于value的区间的右边界,也即是第一个大于value的值的迭代器,也即理解为upper bound。

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(heaters.begin(), heaters.end()); //将散热器位置排序
        int ret = 0; 
        for(auto house : houses) {
            int cur = INT_MAX; //当前房屋所需的最小供热半径
            auto right = lower_bound(heaters.begin(), heaters.end(), house); //找到对应的右侧的散热器位置
            if(right != heaters.end()) cur = *right - house; //若是右侧有散热器,则更新供热半径
            if(right != heaters.begin()) cur = min(cur, house - *(right-1)); //若是左侧也有散热器
            ret = max(cur, ret); //最终结果取各个房屋的供热半径的最大值
        }
        return ret;
    }
};


December 21st : 1154. 一年中的第几天

若是dayOfYear作为常驻进程的一部分,并且频繁调用的话,可以在Solution类中开辟一个前缀和数组,记录当前月的前面月份的日期和,若是只是偶尔调用,则当场加即可。

闰年的定义,我都记不清了,难受(摘自百度百科):

  • 普通闰年:公历年份是4的倍数,且不是100的倍数的,为闰年(如2004年、2020年等就是闰年)。
  • 世纪闰年:公历年份是整百数的,必须是400的倍数才是闰年(如1900年不是闰年,2000年是闰年)
class Solution {
public:
    int dayOfYear(string date) {
        vector<int> days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        for(int i = 1; i <= 12; ++i) days[i] += days[i-1];
        int year = atoi(date.substr(0, 5).c_str()); 
        int month = atoi(date.substr(5, 3).c_str());
        int day = atoi(date.substr(8, 2).c_str());
        cout << year << " " <<  month << " " << day << endl;
        return day + 
               ((((year % 400 == 0 && year % 100 == 0) || (year % 100 != 0 && year % 4 == 0)) && month > 2) ? 
               days[month-1] + 1 : days[month-1]);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值