leetcode:56. 合并区间(数组)

题目:

在这里插入图片描述

分析:

直接使用cmp即可。

无论最后一个是否合并,都可归结到:

vv2.push_back(v);

代码:

class Solution {
public:
static bool cmp(vector<int> &a,vector<int> &b){
        if(a[0] == b[0]) return a[1] < b[1];
        return a[0] < b[0];
}
    vector<vector<int>> merge(vector<vector<int>>& vv) {
        if(vv.size()==0) return vv;
         sort(vv.begin(),vv.end(),cmp);
 vector<vector<int> > vv2;
 vector<int> v=vv[0];
 for(int i=1;i<vv.size();i++)
 {
  if(vv[i][0]<=v[1]) v[1]=max(vv[i][1],v[1]);
  else{
   vv2.push_back(v);
   v=vv[i];
  }
 }
 vv2.push_back(v);
 return vv2;
    }
};
发布了335 篇原创文章 · 获赞 235 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42721412/article/details/105550832
今日推荐