[LeetCode] 56. Merge Interval

Posted 蘑菇君520

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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<Interval> intervals) 
        if (intervals == null) return null;
        if (intervals.length == 0) return new ArrayList<>();
        Collections.sort(intervals, new Comparator<Interval>() 
          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<intervals.size(); i++) 
            Interval interval = intervals.get(i);
            if (end >= 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<Interval> 
        @Override
        public int compare(Interval a, Interval b) 
            return a.start - b.start ;
        
    

    public List<Interval> merge(List<Interval> intervals) 
        Collections.sort(intervals, new IntervalComparator());

        LinkedList<Interval> merged = new LinkedList<Interval>();
        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;
    

以上是关于[LeetCode] 56. Merge Interval的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 56. Merge Intervals

LeetCode56 Merge Intervals

LeetCode 56. 56. Merge Intervals 20170508

java 56.Merge Intervals #LeetCode #Interval

java 56.Merge Intervals #LeetCode #Interval

Leetcode 56: Merge Intervals