区间合并
一个区间可以表示为[start,end],按start排序
List<List<Integer>> list = List.of(List.of(4, 5), List.of(1, 4));
list = list.stream()
.sorted(Comparator.comparingInt(s -> s.get(0)))
.collect(Collectors.toList());
List<List<Integer>> result = new ArrayList<>();
result.add(list.get(0));
for (int i =1;i<list.size();i++) {
List<Integer> curr = list.get(i);
//找到最后一个区间
List<Integer> last = result.get(result.size() - 1);
if (last.get(1) >= curr.get(0)) {
int max = Math.max(last.get(1), curr.get(1));
result.remove(result.size()-1);
result.add(List.of(last.get(0),max));
} else {
//进行下一轮区间
result.add(curr);
}
}
区间交集
def intervalIntersection(A, B):
i, j = 0, 0 # 双指针
res = []
while i < len(A) and j < len(B):
a1, a2 = A[i][0], A[i][1]
b1, b2 = B[j][0], B[j][1]
# 两个区间存在交集
if b2 >= a1 and a2 >= b1:
# 计算出交集,加入 res
res.append([max(a1, b1), min(a2, b2)])
# 指针前进
if b2 < a2: j += 1
else: i += 1
return res