寒假刷题Day24
一、986. 区间列表的交集
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
vector<vector<int>> res;
int i = 0, j = 0, n1 = firstList.size(), n2 = secondList.size();
if(n1 == 0 || n2 == 0) return res;
while(i < n1 && j < n2){
int l = max(firstList[i][0], secondList[j][0]), r = min(firstList[i][1], secondList[j][1]); //有交集
if(l <= r){
res.push_back({l, r});
}
if(firstList[i][1] > secondList[j][1]){
++j;
}
else{
++i;
}
}
return res;
}
};
关键在于两点:
- 满足r1 >= l2 && r2 >= l1则两集合相交。
- 两集合交集为[max(l1, l2), min(r1, r2)]。
二、面试题 16.06. 最小差
class Solution {
public:
int smallestDifference(vector<int>& a, vector<int>& b) {
int i = 0, j = 0, n1 = a.size(), n2 = b.size();
sort(a.begin(), a.end());
sort(b.begin(), b.end());
long ans = LONG_MAX; // 用 long 来避免溢出
while (i < n1 && j < n2) {
long diff = (long)a[i] - (long)b[j]; // 用 long 计算避免溢出
ans = min(ans, abs(diff));
if (diff < 0) {
i++;
} else {
j++;
}
}
return (int)ans;
}
};
我要吐槽这个神人测试用例:
a =
[-2147483648,1]
b =
[2147483647,0]
a[i] - b[j]
可能会超出 int
类型的范围,特别是当 a[i] = -2147483648
且 b[j] = 2147483647
时:
a[ i ] − b[ j ] = −2147483648 − 2147483647 = −4294967295
这个值超出了 int
(32 位有符号整数)的范围([-2^{31}, 2^{31}-1]
),导致溢出。