[LeetCode] 56. Merge Interval

Description

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Solution

思路还是很清楚的,按start从小到大排序,然后遍历整个list,遇到两个重叠的就取更大的end。但是自己实现的不够优雅,在循环外对第一个和最后一个数据做了额外处理。

 public Interval merge(List intervals) {
        if (intervals == null) return null;
        if (intervals.length == 0) return new ArrayList<>();
        Collections.sort(intervals, new Comparator() {
          public int compare(Interval o1, Interval o2) {
              return o1.start - o2.start;
          }  
        });
        // 先拿出第一个数据做初始值
        int start = intervals.get(0).start;
        int end = intervals.get(0).end;
        for (int i=1; i= interval.start) {
                end = Math.max(end, interval.end);
            } else {
                res.add(new Interval(start, end));
                start = interval.start;
                end = interval.end;
            }
        }
        // 这里要对最后一个Interval做额外处理
        res.add(new Interval(start, end));
        return res;
    }

然后看别人的答案,贪吃蛇的写法,甚是优雅~

private class IntervalComparator implements Comparator {
        @Override
        public int compare(Interval a, Interval b) {
            return a.start - b.start ;
        }
    }

    public List merge(List intervals) {
        Collections.sort(intervals, new IntervalComparator());

        LinkedList merged = new LinkedList();
        for (Interval interval : intervals) {
            // if the list of merged intervals is empty or if the current
            // interval does not overlap with the previous, simply append it.
            if (merged.isEmpty() || merged.getLast().end < interval.start) {
                merged.add(interval);
            }
            // otherwise, there is overlap, so we merge the current and previous
            // intervals.
            else {
                merged.getLast().end = Math.max(merged.getLast().end, interval.end);
            }
        }

        return merged;
    }

你可能感兴趣的:(我就会这点算法)