Leetcode C++《热题 Hot 100-38》56.合并区间

Leetcode C++《热题 Hot 100-38》56.合并区间

  1. 题目
    给出一个区间的集合,请合并所有重叠的区间。

示例 1:

输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:

输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 排序之后进行区间合并,时间复杂度平均nlogn(因为用了C++程序自带的sort)
  1. 代码
struct Line {
    int x;
    int y;
    Line(int x1, int y1) {
        x = x1;
        y = y1;
    }
};

class Solution {
public:
    static bool cmp(Line one, Line two) {
        if (two.x > one.x)
            return true;
        if (one.x == two.x && two.y > one.y)
            return true;
        return false;
    }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        //缺乏思路,我们可以先瞅瞅评论在说啥hh
        //暴力法就是排序之后进行合并
        vector<vector<int>> res;
        if (intervals.size() == 0)
            return res;
        vector<Line> tempIntervals;
        for (int i = 0; i < intervals.size(); i++) {
            Line oneInterval(intervals[i][0], intervals[i][1]);
            tempIntervals.push_back(oneInterval);
        }
        sort(tempIntervals.begin(), tempIntervals.end(), cmp);
        vector<int> oneLine;
        oneLine.push_back(tempIntervals[0].x);
        oneLine.push_back(tempIntervals[0].y);
        res.push_back(oneLine);
        for (int i = 1; i < tempIntervals.size(); i++) {
            vector<int> temp = res[res.size()-1];
            int x1 = temp[0];
            int y1 = temp[1];
            int x2 = tempIntervals[i].x;
            int y2 = tempIntervals[i].y;
            if ( x2 == x1 || x2 <= y1)
                res[res.size()-1][1] = max(y1,y2);
            else {
                oneLine.clear();
                oneLine.push_back(tempIntervals[i].x);
                oneLine.push_back(tempIntervals[i].y);
                res.push_back(oneLine);
            }
        }
        return res;
    }
};
发布了205 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104199212
今日推荐