merge-intervals

题目链接

思路

  1. 对于整个列表的start进行升序排序
  2. 搜索 start1,end1 start2,end2
  3. 如果start2>end1的话就continue 否则 将end1改为Max(end1,end2) 删除当前结点(2)
/** * 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; } * } */
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if(intervals==null || intervals.size()<=1){
            return intervals;
        }
        //对链表的start进行升序排序
        Comparator<Interval> comparator = new Comparator<Interval>(){
            public int compare(Interval s1,Interval s2){
                return s1.start-s2.start;
            }
        };
        Collections.sort(intervals,comparator);
        //
        for(int i=1;i<intervals.size();i++){

            if(intervals.get(i).start>intervals.get(i-1).end){

            }else{

                int maxEnd = Math.max(intervals.get(i-1).end, intervals.get(i).end);
                Interval temp = new Interval(intervals.get(i-1).start,maxEnd);
                intervals.set(i-1, temp);
                intervals.remove(i);
                i--;

            }
        }
        return intervals;
    }
}

你可能感兴趣的:(merge-intervals)