Merge Two Sorted Interval Lists

http://www.lintcode.com/zh-cn/problem/merge-two-sorted-interval-lists/

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Solution {
    /**
     * @param list1: one of the given list
     * @param list2: another list
     * @return: the new sorted list of interval
     */
    public List mergeTwoInterval(List list1, List list2) {
        // write your code here
        list1.addAll(list2);
        Collections.sort(list1, new Comparator() {
            @Override
            public int compare(Interval o1, Interval o2) {
                return o1.start - o2.start;
            }
        });
        for (int i = 0; i < list1.size() - 1; i++) {
            Interval first = list1.get(i);
            Interval next = list1.get(i + 1);
            if (first.end < next.start) {
                continue;
            } else {
                first.end = Math.max(next.end, first.end);
                list1.remove(i + 1);
                i--;
            }
        }
        return list1;
    }
}

你可能感兴趣的:(Merge Two Sorted Interval Lists)