LintCode —— 30.插入区间

给出一个无重叠的按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

样例

插入区间[2, 5] 到 [[1,2], [5,9]],我们得到 [[1,9]]

插入区间[3, 4] 到 [[1,2], [5,9]],我们得到 [[1,2], [3,4], [5,9]]


package lintcode;

import ds.Interval;

import java.util.LinkedList;
import java.util.List;

/**
 * Class Name  : InsertInterval_30
 * Describe    :
 * Create User : Leon
 * Create Date : 2018/1/31
 * Create Time : 16:27
 **/

public class InsertInterval_30 {

    public static void main(String[] args) {
        List intervals = new LinkedList();
        intervals.add(new Interval(1, 2));
        intervals.add(new Interval(5, 9));
        System.out.println(insert(intervals, new Interval(3, 4)));

    }

    public static List insert(List intervals, Interval newInterval) {
        List result = new LinkedList();
        result.add(newInterval);
        for (int i = 0; i < intervals.size(); i++) {
            Interval ri = result.remove(result.size() - 1);
            result.addAll(merge(intervals.get(i), ri));
        }
        return result;
    }

    public static List merge(Interval inter1, Interval inter2) {
        List list = new LinkedList();
        if (inter2.start <= inter1.start) {
            if (inter2.end >= inter1.end) {
                list.add(inter2);
            } else if (inter2.end >= inter1.start) {
                list.add(new Interval(inter2.start, inter1.end));
            } else if (inter2.end < inter1.start) {
                list.add(inter2);
                list.add(inter1);
            }
            return list;
        } else {
            return merge(inter2, inter1);
        }
    }
}


你可能感兴趣的:(LintCode)