力扣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);
	}
}
相关推荐
tryxr6 分钟前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_310 分钟前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia21 分钟前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z36 分钟前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.40 分钟前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好1 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.1 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark1 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
yuanxi2001 小时前
卡塔尔能源公司LNG扩建项目首条生产线预计明年投运:大客户销售的5个判断
职场和发展·创业创新·学习方法
小陈phd2 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法