Leetcode PHP题解--D122 1154. Day of the Year


题目链接

1154. Day of the Year

题目分析

这道题目比较简单,给定YYYY-MM-DD格式的日期,返回这一天是这一年的第几天。

思路

首先要知道每个月的天数是不一样的,那么我们先把它存起来。

然后用array_slice获取当月之前的所有月份天数,并用array_sum函数计算总和。再加上DD部分即可。

需要注意的是,只有当待求月份大于2月时,才需要通过判断是否是闰年来加1天。如果待求月份为1月或2月时,不需要考虑闰年。

最终代码

<?php
class Solution {

    /**
     * @param String $date
     * @return Integer
     */
    public $daysOfMonth = [
        31,28,31,30,31,30,
        31,31,30,31,30,31,
    ];
    function dayOfYear($date) {
        list($year, $month, $day) = explode('-', $date);
        $year = intval($year);
        $month = intval($month);
        $day = intval($day);
        $isLeap = intval(($month>2) && ($year%4 == 0) && ($year%100!=0));

        return array_sum(array_slice($this->daysOfMonth,0,$month-1)) + $day + $isLeap;
    }
}

不过这题只打败了41.67%,有提升空间。

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Laravel 8 正式发布,一起来看看有哪些新特性吧

>> 下一篇: Leetcode PHP题解--D123 661. Image Smoother