Thursday, January 8, 2015

LeetCode 56: Merge Intervals

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].
/**
 * 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 {
    private List<Interval> aux;
    
    public List<Interval> merge(List<Interval> intervals) {
        if (intervals.size() <= 1)
            return intervals;
            
        // Step 1: Sort 'intervals' according to 'start'
        Collections.sort(intervals, new Comparator<Interval>()
                                    {
                                        public int compare(Interval a, Interval b)
                                        {
                                            if (a.start > b.start)
                                                return 1;
                                            else if (a.start < b.start)
                                                return -1;
                                            else
                                                return 0;
                                        }
                                    });
        
        // Step 2: Merge 'intervals'
        List<Interval> result = new LinkedList<>();
        result.add(intervals.get(0));
        int cnt = 0;
        
        for (int i = 1; i < intervals.size(); i++)
        {
            if (intervals.get(i).start <= result.get(cnt).end)
                result.get(cnt).end = Math.max(result.get(cnt).end, intervals.get(i).end);
            else
            {
                result.add(intervals.get(i));
                cnt++;
            }
        }
        
        return result;
    }
}

No comments:

Post a Comment