
image.png
雙指針,注意單個數(shù)組的前面可能重疊,后面也可能。
遇到 [1,3],[2,4]這種重疊的記得left指針要拋棄[1,3]這種end更小的然后left++,因為下一個重疊肯定跟[1,3]沒關(guān)系了。
如果沒有重疊那就把前面那個指針++。
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
if(firstList.size()==0||secondList.size()==0){
return {};
}
int l1=0;
int l2=0;
vector<vector<int>>res;
// 看誰的start更小,然后判斷是否有交集,有交集那么start更小但是end也更小的拋棄然后l1++,否則拋棄l2
while(l1<firstList.size()&&l2<secondList.size()){
int p1=max(firstList[l1][0],secondList[l2][0]);
int p2=min(firstList[l1][1],secondList[l2][1]);
if(p1<=p2){
res.push_back(vector<int>{p1,p2});
if(firstList[l1][1]<secondList[l2][1]){
l1++;
}else{
l2++;
}
}else{
if(firstList[l1][1]<secondList[l2][0]){
l1++;
}
else{
l2++;
}
}
}
return res;
}
};