题解 | #合并区间#

合并区间

http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

新建一个类代理原来的对象实现Comparable接口进行排序

import java.util.Arrays;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collections;
/**
 * 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 {
    class IntervalProxy implements Comparable{
        Interval interval;
        IntervalProxy(Interval interval){
            this.interval = interval;
        }
        @Override
        public int compareTo(Object o) {
            IntervalProxy intervalProxys = (IntervalProxy) o;
            return this.interval.start < intervalProxys.interval.start?-1:1;
        }
    }
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if(intervals == null || intervals.size() == 0){
            return new ArrayList<Interval>();
        }
        ArrayList<IntervalProxy> intervalProxys = new ArrayList<IntervalProxy>();
        Iterator<Interval> iterator = intervals.iterator();
        while(iterator.hasNext()){
            intervalProxys.add(new IntervalProxy(iterator.next()));
        }
        Collections.sort(intervalProxys);
        ArrayList<Interval> newIntervals = new ArrayList<Interval>();
        newIntervals.add(new Interval(intervalProxys.get(0).interval.start,intervalProxys.get(0).interval.end));
        for(int i = 1; i < intervalProxys.size(); i++){
            while(i < intervalProxys.size()){
                if(newIntervals.get(newIntervals.size()-1).end >= intervalProxys.get(i).interval.start){
                    newIntervals.get(newIntervals.size()-1).end = Math.max(newIntervals.get(newIntervals.size()-1).end,intervalProxys.get(i).interval.end);
                }else{
                    newIntervals.add(new Interval(intervalProxys.get(i).interval.start,intervalProxys.get(i).interval.end));
                }
                i++;
            }
        }
        return newIntervals;
    }
}
全部评论

相关推荐

吃不饱的肱二头肌很想退休:tnnd 我以为选妹子呢,亏我兴高采烈的冲进来😠
投递快手等公司10个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务