这道题我第一次做了好久都没搞定,这次一下就ok了。
上下两个指针,其实就两种情况,first和second没有交集。如果没有,就让小的那个指针++,如果有交集,就做出这个集合,完了第二个值小的那条链的指针++。
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
int first = 0,second=0;
int nfirst = static_cast<int>(firstList.size()), nsecond = static_cast<int>(secondList.size());
vector<vector<int> > ret;
while(first<nfirst && second<nsecond)
{
if(firstList[first].back()<secondList[second].front())
++first;
else if(secondList[second].back()<firstList[first].front())
++second;
else
{
ret.push_back({max(firstList[first].front(),secondList[second].front()), min(firstList[first].back(),secondList[second].back())});
if(firstList[first].back()>secondList[second].back())
++second;
else
++first;
}
}
return ret;
}
};