跳至主要內容

56. 合并区间


56. 合并区间

🟠   🔖  数组 排序  🔗 力扣open in new window LeetCodeopen in new window

题目

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.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]

Output: [[1,5]]

Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Constraints:

  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 10^4

题目大意

以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间

解题思路

  • 一个区间可以表示为 [start, end],先按区间的 start 排序
  • 对于几个相交区间合并后的结果区间 xx.start 一定是这些相交区间中 start 最小的,x.end 一定是这些相交区间中 end 最大的
  • 由于已经排了序,x.start 很好确定,求 x.end 也很容易,可以类比在数组中找最大值的过程。

代码

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
	let res = [];

	// 先按区间的 `start` 排序
	intervals = intervals.sort((a, b) => a[0] - b[0]);
	for (let i = 0; i < intervals.length; i++) {
		let start = intervals[i][0],
			end = intervals[i][1];

		// 如果区间相交,求结果区间 [start, end]
		while (intervals[i + 1] && inRange(intervals[i + 1], start, end)) {
			start = Math.min(start, intervals[i + 1][0]);
			end = Math.max(end, intervals[i + 1][1]);
			i++;
		}
		res.push([start, end]);
	}
	return res;
};

// 判断区间是否相交
var inRange = function (interval, start, end) {
	let [m, n] = interval;
	if (m < start && n < start) return false;
	if (m > end && n > end) return false;
	return true;
};

相关题目

题号标题题解标签难度力扣
57插入区间[✓]数组🟠🀄️open in new window 🔗open in new window
252会议室 🔒数组 排序🟢🀄️open in new window 🔗open in new window
253会议室 II 🔒贪心 数组 双指针 3+🟠🀄️open in new window 🔗open in new window
495提莫攻击数组 模拟🟢🀄️open in new window 🔗open in new window
616给字符串添加加粗标签 🔒字典树 数组 哈希表 2+🟠🀄️open in new window 🔗open in new window
715Range 模块设计 线段树 有序集合🔴🀄️open in new window 🔗open in new window
759员工空闲时间 🔒数组 排序 堆(优先队列)🔴🀄️open in new window 🔗open in new window
763划分字母区间[✓]贪心 哈希表 双指针 1+🟠🀄️open in new window 🔗open in new window
986区间列表的交集[✓]数组 双指针🟠🀄️open in new window 🔗open in new window
2158每天绘制新区域的数量 🔒线段树 数组 有序集合🔴🀄️open in new window 🔗open in new window
2213由单个字符重复的最长子字符串线段树 数组 字符串 1+🔴🀄️open in new window 🔗open in new window
2276统计区间中的整数数目设计 线段树 有序集合🔴🀄️open in new window 🔗open in new window
2406将区间分为最少组数[✓]贪心 数组 双指针 3+🟠🀄️open in new window 🔗open in new window
2446判断两个事件是否存在冲突数组 字符串🟢🀄️open in new window 🔗open in new window
2580统计将重叠区间合并成组的方案数数组 排序🟠🀄️open in new window 🔗open in new window
2848与车相交的点数组 哈希表 前缀和🟢🀄️open in new window 🔗open in new window
3169无需开会的工作日数组 排序🟠🀄️open in new window 🔗open in new window
3323通过插入区间最小化连通组 🔒数组 二分查找 排序 1+🟠🀄️open in new window 🔗open in new window