1. 程式人生 > >56. Merge Intervals - LeetCode

56. Merge Intervals - LeetCode

turn 實現 else sta 坐標軸 return scrip 分享圖片 img

Question

56. Merge Intervals

技術分享圖片

Solution

題目大意:

一個坐標軸,給你n個範圍,把重疊的範圍合並,返回合並後的坐標對

思路:

先排序,再遍歷判斷下一個開始是否在上一個範圍內,如果在且結束坐標大於上一個坐標就合並

Java實現:

public List<Interval> merge(List<Interval> intervals) {
    if (intervals == null || intervals.size() == 0) return intervals;

    // sort
    intervals = intervals.stream()
        .sorted(Comparator.comparing(e -> e.start))
        .collect(Collectors.toList());

    List<Interval> result = new ArrayList<>();
    int start = intervals.get(0).start;
    int end = intervals.get(0).end;
    for (int i = 1; i < intervals.size(); i++) {
        Interval tmp = intervals.get(i);
        if (tmp.start >= start && tmp.start <= end) {
            if (tmp.end > end) end = tmp.end;
        } else {
            result.add(new Interval(start, end));
            start = tmp.start;
            end = tmp.end;
        }
    }
    result.add(new Interval(start, end));
    return result;
}

56. Merge Intervals - LeetCode