力扣hot100 合并区间 排序 贪心

Problem: 56. 合并区间

复杂度

时间复杂度: O ( n log ⁡ n ) O(n\log{n}) O(nlogn)

空间复杂度: O ( n ) O(n) O(n)

Code

Java 复制代码
class Solution {
	public int[][] merge(int[][] intervals)
	{
		Arrays.sort(intervals, (int[] a, int[] b) -> {
			return a[0] - b[0];
		});// 按照数组的第一个元素升序排序
		int n = intervals.length;
		int[][] res = new int[n][2];// 记录每个数组的左右边界
		int idx = -1;
		for (int[] a : intervals)
		{
//			第一个数组       或  当前数组不能融入 当前已有的数组 (左边界 > 已有数组的右边界)
			if (idx == -1 || a[0] > res[idx][1])
				res[++idx] = a;// 把当前数组 加入 结果
			else
//				可以融入的情况,右边界取较大值
				res[idx][1] = Math.max(a[1], res[idx][1]);
		}
		//res数组经过合并区间,长度 <= n
		return Arrays.copyOf(res, idx + 1);
	}
}
相关推荐
Lazyafei2 小时前
滑动窗口:扩张与收缩的动态区间
算法
FRing033 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
老歌老听老掉牙3 小时前
三个等价答案:遗传算法如何逼近 Branin 函数
c++·算法·ga
是main不是漫3 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法
geovindu4 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Navigator_Z6 小时前
LeetCode //C - 1328. Break a Palindrome
c语言·算法·leetcode
电科_银尘6 小时前
【大模型算法与工程 46】vLLM部署入门:模型服务、请求与运行观测
算法·vllm
AskHarries6 小时前
社区运营打法
算法
人间乄惊鸿客1 天前
c++ 右值
c++·算法