美文网首页
56.合并区间

56.合并区间

作者: _道友请留步_ | 来源:发表于2018-05-14 13:54 被阅读0次
    /**
     * 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; }
     * }
     */
    class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            List<Integer> list = new ArrayList<>();
            List<Interval> result = new ArrayList<>();
            if(intervals.size() == 0){
                return result;
            }
            HashMap<Integer, Interval> map = new HashMap<>();
            for(int i = 0; i < intervals.size(); i++){
                Interval interval = intervals.get(i);
                if(!map.containsKey(interval.start)){
                    list.add(interval.start);
                    map.put(interval.start, interval);
                } else {
                    Interval lastInterval = map.get(interval.start);
                    int end = Math.max(lastInterval.end, interval.end);
                    interval = new Interval(lastInterval.start, end);
                    map.put(interval.start, interval);
                }
            }
            Collections.sort(list);
            for(int i = 0 ; i < list.size()-1;i++){
                Interval interval = map.get(list.get(i));
                if(interval.end >= list.get(i+1)){
                    Interval next = map.get(list.get(i+1));
                    Interval mergedInterval = new Interval(interval.start, Math.max(interval.end, next.end));
                    map.put(list.get(i+1), mergedInterval);
                } else {
                    result.add(interval);
                }
            }
            result.add(map.get(list.get(list.size()-1)));
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:56.合并区间

          本文链接:https://www.haomeiwen.com/subject/wsoddftx.html