力扣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);
	}
}
相关推荐
春日见4 分钟前
如何避免代码冲突,拉取分支
linux·人工智能·算法·机器学习·自动驾驶
副露のmagic6 分钟前
更弱智的算法学习 day59
算法
u0109272711 小时前
C++中的RAII技术深入
开发语言·c++·算法
2401_832131952 小时前
模板错误消息优化
开发语言·c++·算法
金枪不摆鳍2 小时前
算法--二叉搜索树
数据结构·c++·算法
近津薪荼2 小时前
优选算法——双指针6(单调性)
c++·学习·算法
helloworldandy3 小时前
高性能图像处理库
开发语言·c++·算法
2401_836563183 小时前
C++中的枚举类高级用法
开发语言·c++·算法
bantinghy3 小时前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
chao1898443 小时前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法