题解 | #合并区间#

合并区间

https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

/**
 * struct Interval {
 *	int start;
 *	int end;
 *	Interval(int s, int e) : start(start), end(e) {}
 * };
 */
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param intervals Interval类vector 
     * @return Interval类vector
     */
    vector<Interval> merge(vector<Interval>& intervals) {
        auto cmp = [](const Interval& a, const Interval& b) {
            return a.start < b.start;
        };
        if (intervals.empty()) {
            return {};
        }
        sort(begin(intervals), end(intervals), cmp);
        vector<Interval> result;
        Interval cur;
        cur.start = intervals[0].start;
        cur.end = intervals[0].end;
        for (int i = 1; i < intervals.size(); ++i) {
            int s = intervals[i].start;
            int e = intervals[i].end;
            if (s <= cur.end) {
                // 重叠
                cur.end = max(cur.end, e);
            } else {
                // 不重叠
                result.emplace_back(cur.start, cur.end);
                cur.start = s;
                cur.end = e;
            }
        }
        result.emplace_back(cur.start, cur.end);
        return result;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务