Merge Two Sorted Interval Lists

本文详细介绍了一种用于合并两个已排序的区间列表的算法,并通过实例展示了如何将这些区间合并为一个新的排序列表。该算法首先将两个列表合并,再进行区间融合,确保最终输出的区间列表既不重复也不遗漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Merge two sorted (ascending) lists of interval and return it as a new sorted list. The new sorted list should be made by splicing together the intervals of the two lists and sorted in ascending order.

Example

Example1

Input: list1 = [(1,2),(3,4)] and list2 = [(2,3),(5,6)]
Output: [(1,4),(5,6)]
Explanation:
(1,2),(2,3),(3,4) --> (1,4)
(5,6) --> (5,6)

Example2

Input: list1 = [(1,2),(3,4)] and list2 = [(4,5),(6,7)]
Output: [(1,2),(3,5),(6,7)]
Explanation:
(1,2) --> (1,2)
(3,4),(4,5) --> (3,5)
(6,7) --> (6,7)

Notice

  • The intervals in the given list do not overlap.
  • The intervals in different lists may overlap.

思路:先merge成一个list,然后转换成我熟悉的,merge 一个list

/**
 * Definition of Interval:
 * public classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 * }
 */

public class Solution {
    /**
     * @param list1: one of the given list
     * @param list2: another list
     * @return: the new sorted list of interval
     */
    public List<Interval> mergeTwoInterval(List<Interval> list1, List<Interval> list2) {
        List<Interval> list = new ArrayList<Interval>();
        if(list1 == null || list1.size() == 0) return list2;
        if(list2 == null || list2.size() == 0) return list1;
        
        
        List<Interval> templist = new ArrayList<Interval>();
        int i = 0; int j = 0;
        while(i < list1.size() && j < list2.size()){
            Interval a = list1.get(i);
            Interval b = list2.get(j);
            if(a.start < b.start){
                templist.add(a);
                i++;
            } else {
                templist.add(b);
                j++;
            }
        }
        
        while(i < list1.size()){
            templist.add(list1.get(i));
            i++;
        }
        
        while(j < list2.size()){
            templist.add(list2.get(j));
            j++;
        }
        
        return mergeInterveral(templist);
    }
    
    private List<Interval> mergeInterveral(List<Interval> list) {
        List<Interval> res = new ArrayList<Interval>();
        Interval cur = list.get(0);
        for(int i = 1; i < list.size(); i++){
            Interval next = list.get(i);
            if(cur.end >= next.start){
                cur = new Interval(cur.start, Math.max(cur.end, next.end));
            } else {
                // cur.end < next.start;
                res.add(cur);
                cur = next;
            }
        }
        res.add(cur);
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值