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

LeetCode - Merge Intervals

时间:2015-12-27 12:02:20      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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].

思路:

先根据start排序,然后合并

package interval;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Interval {
    int start;
    int end;

    Interval() {
        start = 0;
        end = 0;
    }

    Interval(int s, int e) {
        start = s;
        end = e;
    }
} 

public class MergeIntervals {

    public List<Interval> merge(List<Interval> intervals) {
        int n = 0;
        if (intervals == null || (n = intervals.size()) < 2) return intervals;
        Collections.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval a, Interval b) {
                return a.start == b.start ? (a.end - b.end) : (a.start - b.start);
            }
        });
        
        int cur = 0;
        for (int i = 1; i < n; ++i) {
            if (overlapped(intervals.get(cur), intervals.get(i))) {
                Interval newInterval = new Interval(intervals.get(cur).start, 
                        intervals.get(i).end > intervals.get(cur).end ? intervals.get(i).end : intervals.get(cur).end);
                intervals.set(cur, newInterval);
            } else {
                intervals.set(++cur, intervals.get(i));
            }
        }
        
        return intervals.subList(0, cur + 1);
    }
    
    private boolean overlapped(Interval a, Interval b) {
        return a.start <= b.start ? a.end >= b.start : overlapped(b, a);
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Interval> intervals = new ArrayList<Interval>();
        intervals.add(new Interval(1,4));
        intervals.add(new Interval(0,2));
        intervals.add(new Interval(3,5));
        //intervals.add(new Interval(15,18));
        MergeIntervals m = new MergeIntervals();
        List<Interval> res = m.merge(intervals);
        for (Interval i : res) {
            System.out.println("[" + i.start + ", " + i.end + "]");
        }
    }

}

 

LeetCode - Merge Intervals

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5079660.html

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