1. 程式人生 > >leetcode56- Merge Intervals- medium

leetcode56- Merge Intervals- medium

lap val 如果 arr crt over log ping end

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

先寫comparator按照interval的開始時間出現早晚排好序。接著開始遍歷每個interval,如果和上一個有交叉(crt.start <= prev.end),那就改上一個的end為更持久的一個,如果和上一個沒有交叉,那就把之前記錄的間隔推入結果中,重新開始新的檢查。

1.O(n)空間:

/**
 * 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 { private Comparator<Interval> comparator = new Comparator<Interval>(){ public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }; public List<Interval> merge(List<Interval> intervals) { List
<Interval> result = new ArrayList<Interval>(); if (intervals == null || intervals.size() == 0) { return result; } Collections.sort(intervals, comparator); int start = intervals.get(0).start; int end = intervals.get(0).end;
for (int i = 1; i < intervals.size(); i++) { Interval crt = intervals.get(i); if (crt.start <= end) { end = Math.max(end, crt.end); } else { result.add(new Interval(start, end)); start = crt.start; end = crt.end; } } result.add(new Interval(start, end)); return result; } }

2.O(1)空間,原地合並

/**
 * 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 {
    
    private Comparator<Interval> comparator = new Comparator<Interval>(){
        public int compare(Interval i1, Interval i2) {
            return i1.start - i2.start;
        }
    };
    
    public List<Interval> merge(List<Interval> intervals) {
        
        List<Interval> result = new ArrayList<Interval>();
        if (intervals == null || intervals.size() == 0) {
            return result;
        }
        
        Collections.sort(intervals, comparator);
        
        Interval last = intervals.get(0);
        for (int i = 1; i < intervals.size(); i++) {
            Interval crt = intervals.get(i);
            if (crt.start <= last.end) {
                last.end = Math.max(last.end, crt.end);
            } else {
                result.add(last);
                last = crt;
            }
        }
        result.add(last);
        
        return result;
    }    
}

leetcode56- Merge Intervals- medium