题解 | #合并区间#

合并区间

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;
    }
}
全部评论

相关推荐

牛客771574427号:恭喜你,华杰
点赞 评论 收藏
分享
11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务