码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Merge Intervals

时间:2016-07-01 16:25:47      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://blog.csdn.net/itismelzp/article/details/51800491

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!