xinyu04

导航

LeetCode 56 Merge Intervals 排序+模板

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Solution

按第一个端点进行排序即可:
sort(intervals.begin(), intervals.end(), [](const vector<int>& v1, const vector<int>& v2){return v1[0]<v2[0];});

点击查看代码
class Solution {
private:
   
    
    vector<vector<int>> ans;
    
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int n = intervals.size();
        
        if(n<=1)return intervals;
        else{
            //sort(intervals.begin(), intervals.end(), [](const vector<int> &v1, const vector<int> &v2){ return v1[0] < v2[0]; });
            sort(intervals.begin(), intervals.end(), [](const vector<int>& v1, const vector<int>& v2){return v1[0]<v2[0];});
            
            int st = intervals[0][0], ed = intervals[0][1];
            int i=1;
            while(i<n){
                if(intervals[i][0]<=ed){
                    if(intervals[i][1]>ed)ed = intervals[i][1],i++;
                    else i++;
                }
                else{
                    ans.push_back({st,ed});
                    st = intervals[i][0];
                    ed = intervals[i][1];
                    i++;
                }
            }
            ans.push_back({st,ed});
        }
        return ans;
    }
};

posted on 2022-07-19 21:42  Blackzxy  阅读(22)  评论(0编辑  收藏  举报