一、Problem
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
二、Solution
方法一:枚舉
- 直接算兩個日期之間隔的天數比較繁瑣,娶一個相對值,然後,算出兩個日期到這個相對值的各自天數 dd1 和 dd2…
- 最後返回 abs(dd1 - dd2) 即可…
class Solution {
int[] days= {0,31,28,31,30,31,30,31,31,30,31,30,31};
public int daysBetweenDates(String date1, String date2) {
String[] ss1 = date1.split("-");
String[] ss2 = date2.split("-");
int y1 = Integer.parseInt(ss1[0]), y2 = Integer.parseInt(ss2[0]);
int m1 = Integer.parseInt(ss1[1]), m2 = Integer.parseInt(ss2[1]);
int d1 = Integer.parseInt(ss1[2]), d2 = Integer.parseInt(ss2[2]);
return Math.abs(gap(y2, m2, d2) - gap(y1, m1, d1));
}
int gap(int yy, int mm, int dd) {
for (int y = 1971; y < yy; y++) {
dd += 365;
if (isLeep(y))
dd++;
}
for (int m = 1; m < mm; m++)
dd += days[m];
if (isLeep(yy) && mm > 2) dd++; //注
return dd;
}
boolean isLeep(int y) {
return y % 4 == 0 && y % 100 != 0 || y % 400 == 0;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
方法二:庫函數
額…
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Solution {
public int daysBetweenDates(String date1, String date2) {
SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parse1 = null;
Date parse2 = null;
try {
parse1 = sdFormat.parse(date1);
parse2 = sdFormat.parse(date2);
} catch(ParseException e) {
e.printStackTrace();
}
long time = parse1.getTime();
long time2 = parse2.getTime();
long diff = time2 - time;
return Math.abs((int)(diff / 1000 * 24 * 60 * 60));
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,