Merge intervals (C++ solution)

topic

Use an array  intervals to represent a set of several intervals, where a single interval is  intervals[i] = [starti, endi] . Please merge all overlapping intervals and return  an array of non-overlapping intervals that exactly covers all intervals in the input  .

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
 Output: [[1,6],[8,10],[15,18]]
 Explanation: The intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]
 Output: [[1,5]]
 Explanation: The intervals [1,4] and [4,5] can be considered as overlapping intervals.

C++ code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

/*
* 合并区间问题
* 排序,定义区间的左右两边数字
* 如果当前区间的左端点在数组 merged 中最后一个区间的右端点之后,
那么它们不会重合,我们可以直接将这个区间加入数组 merged 的末尾
* 否则,它们重合,我们需要用当前区间的右端点更新数组 merged 中最后一个区间的右端点
*/
vector<vector<int>> merge(vector<vector<int>>& intervals) {
	if (intervals.size() == 0) {
		return {};
	}
	sort(intervals.begin(), intervals.end());
	vector<vector<int>> merged;
	for (int i = 0; i < intervals.size(); ++i) {
		int L = intervals[i][0], R = intervals[i][1];
		if (!merged.size() || merged.back()[1] < L) {
			merged.push_back({ L, R });
		}
		else {
			merged.back()[1] = max(merged.back()[1], R);
		}
	}
	return merged;
}

int main() {
	vector<vector<int>> intervals = { {1,3},{2,6},{8,10},{15,18} };
	vector<vector<int>> merged = merge(intervals);
	for (int i = 0; i < merged.size(); ++i) {
		for (int j = 0; j < merged[0].size(); ++j) {
			cout << merged[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}

analyze

Merge interval problems, sort, and define the numbers on the left and right sides of the interval. If the left endpoint of the current interval is after the right endpoint of the last interval in the array merged, then they will not overlap and we can directly add this interval to the end of the array merged; otherwise, they overlap and we need to update with the right endpoint of the current interval The right endpoint of the last interval in the array merged.

Guess you like

Origin blog.csdn.net/m0_62275194/article/details/133990585