LeetCode:Merge Intervals

Posted walker lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Merge Intervals相关的知识,希望对你有一定的参考价值。

Merge Intervals




Total Accepted: 71689 Total Submissions: 275494 Difficulty: Hard

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

Subscribe to see which companies asked this question

Hide Tags
 Array Sort

















问题很简单,直接看代码。


java code:

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        
        List<Interval> result = new ArrayList<>();
        if(intervals == null || intervals.size() == 0) return result;
        
        Collections.sort(intervals, new Comparator<Interval>(){
            @Override
            public int compare(Interval val1, Interval val2) {
                return Integer.compare(val1.start, val2.start);
            }
        });
        
        int start = intervals.get(0).start;
        int end = intervals.get(0).end;
        
        for(Interval val: intervals) {
            if(val.start <= end) {
                end = Math.max(end, val.end);
            }else{
                result.add(new Interval(start, end));
                start = val.start;
                end = val.end;
            }
        }
        result.add(new Interval(start, end));
        return result;
    }
}


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

[LeetCode] Merge Intervals

[Leetcode] merge intervals 合并区间

[Leetcode] Merge Sorted Array

LeetCode——Merge Two Sorted Lists

LeetCode:Merge Sorted Array

Microsoft leetcode(Merge K Sorted Lists)