leetcode : Merge Intervals [对象排序 + List转换成数组] !!! 基本功

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

 

 

 

tag: 对象排序comparator, List转换成数组

 

/**
 * 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; }
 * }
 */
 
 // list 与数组相互转换
public class Solution {
    public List merge(List intervals) {
        List result = new ArrayList();
        if(intervals == null || intervals.size() == 0) {
            return result;
        }
        int size = intervals.size();
        
        Interval[] intervalArr = intervals.toArray(new Interval[size]);
        Arrays.sort(intervalArr, new Comparator(){
            public int compare(Interval interval1, Interval interval2) {
                return interval1.start - interval2.start;
            }
        });
        
        Interval mover = intervalArr[0];
        for(int i = 1; i < size; i++) {
            if(mover.end < intervalArr[i].start ) {
                result.add(mover);
                mover = intervalArr[i];
            } else {
                mover.end = Math.max(mover.end, intervalArr[i].end);
            }
        }
        result.add(mover);
        return result;
    }
}

  

 

 

转载于:https://www.cnblogs.com/superzhaochao/p/6473843.html

你可能感兴趣的:(leetcode : Merge Intervals [对象排序 + List转换成数组] !!! 基本功)