LeetCode 986. 区间列表的交集

题目描述

🔥 986. 区间列表的交集

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
func intervalIntersection(firstList [][]int, secondList [][]int) [][]int {
	res := make([][]int, 0)
	i, j := 0, 0
	for i < len(firstList) && j < len(secondList) {
		// 找到两个区间起始点的最大值。
		start := max(firstList[i][0], secondList[j][0])
		// 找到两个区间结束点的最小值。
		end := min(firstList[i][1], secondList[j][1])
		// 检查是否实际存在交叉区间。
		if start <= end {
			// 将交叉区间[start, end]添加到结果中。
			res = append(res, []int{start, end})
		}
		// 移动对应于具有较小结束点的区间的指针。
		if firstList[i][1] < secondList[j][1] {
			i++
		} else {
			j++
		}
	}
	return res
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

🍏 点击查看 Java 题解

1
write your code here

相似题目

题目 难度 题解
合并区间 Medium  
合并两个有序数组 Easy  
员工空闲时间 Hard  
本文作者:
本文链接: https://hgnulb.github.io/blog/71305127
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!