6184. 统计共同度过的日子数6184. 统计共同度过的日子数
y总这周第一哎,来学习一下。
日期相交问题
计算m月d日是这一年的第几天,然后套公式。
AC代码:
class Solution {
public:
int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int get(string s) {
int res = 0;
int m, d;
sscanf(s.c_str(), "%d-%d", &m, &d);
for (int i = 1; i < m; i ++ ) res += months[i];
return res + d;
}
int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {
int a = get(arriveAlice), b = get(leaveAlice);
int c = get(arriveBob), d = get(leaveBob);
return max(0, min(b, d) - max(a, c) + 1);
}
};
来自y总:LeetCode 2409. 统计共同度过的日子数 - AcWing
第二题经典贪心题
最大匹配问题,匈牙利算法时间复杂度O(n^3),肯定会超时,所以得用贪心。
第二题又看到了y总的闫氏贪心分析法,哈哈哈。
class Solution {
public:
int matchPlayersAndTrainers(vector<int>& a, vector<int>& b) {
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int res = 0;
for (int i = 0, j = 0; i < a.size() && j < b.size(); i ++ ) {
while (j < b.size() && a[i] > b[j]) j ++ ;
if (j < b.size() && a[i] <= b[j]) {
res ++ ;
j ++ ;
}
}
return res;
}
};