3 minutes
Leetcode 1154
Note: I know that the second solution is pretty un-orthidoxed because we would have to change a lot of stuff if the input changed.
How the first solution works:
The first solution is pretty simple:
- We find the year month and day (Note: We call the day
res
because the day is only used for adding to the result) - We also have an array of the number of days per month
- Then we check whether it is a leep year, if so add
1
day to the result. - Then we loop through every month that has passed (From Jan to
month
) and add their days tores
. - Then we can return
res
.
The First solution O(n), O(12)
func dayOfYear(date string) int {
days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
year, _ := strconv.Atoi(date[: 4])
month, _ := strconv.Atoi(date[5 : 7])
res, _ := strconv.Atoi(date[8 :])
if month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
res++
}
for month - 1 > 0 {
res += days[month - 2]
month--
}
return res
}
How the second solution works:
- In this solution we also find the
year
,month
, andres
(res ==
current day of the month). - Then we check whether it is a leep year, if so add
1
day to the result. - Then we do
res += 30 * (month - 1)
. We do this because all the days in every month (Not including leap years for we have handeled leep years before we dores += 30 * (month - 1)
) are either30, 31
, or28
, so for all months that have31
days we can add1
tores
, and for Feburary we can subtract2
fromres
. - Next we have
if month > 2 { res -= 2 }
we know that feburary has passed so we can subtract2
fromres
. - Now you might be confused by:
if month < 9 { res += month / 2 } else { res += (month - 7) / 2 + 1 }
because when adding1
per month you would think that we would domonth
The second solution O(1), O(1)
func dayOfYear(date string) int {
year, _ := strconv.Atoi(date[: 4])
month, _ := strconv.Atoi(date[5 : 7])
res, _ := strconv.Atoi(date[8 :])
if month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
res++
}
res += 30 * (month - 1)
if month > 2 {
res -= 2
}
if month < 9 {
res += month / 2
} else {
res += (month - 7) / 2 + 1
}
return res
}
Read other posts