Leetcode|Medium|Interval Greedy|56. Merge Interval

Insert picture description here

1 Greedy algorithm traverses once

Insert picture description here

  • Merge if overlap
  • Add if not overlapping
class Solution {
    
    
public:
    static bool cmp(const vector<int>& a, const vector<int>& b) {
    
    
        return a[0] < b[0];
    }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
    
    
        if (intervals.empty()) return {
    
    };
        // 起始点靠前的优先排列
        sort(intervals.begin(), intervals.end(), cmp);
        vector<vector<int>> solution;
        solution.emplace_back(intervals[0]);
        for (int i = 1; i < intervals.size(); i++) {
    
    
            // 1.重叠则合并
            if (intervals[i][0] <= solution.back()[1]) 
                solution.back()[1] = max(solution.back()[1], intervals[i][1]);
            // 2.不重叠则添加
            else solution.emplace_back(intervals[i]);
        }
        return solution;
    }
};

Insert picture description here

Thanks

The picture comes from the official account of "Code Random Record", welcome everyone to pay attention to the official account of this big guy

Guess you like

Origin blog.csdn.net/SL_World/article/details/114936218