力扣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);
	}
}
相关推荐
在猴站学算法14 小时前
(《统计学习方法》(第2版) 李航)第2章 感知机算法
学习·算法·机器学习·统计学习
Rainmicro14 小时前
【无标题】
java·数据库·算法
NEFU_Jyj1 天前
牛客周赛R168
算法
文丑颜不良啊1 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z1 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH1 天前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶1 天前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊1 天前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊1 天前
C++算法 二分查找篇(上)
开发语言·c++·算法