* 56. Merge Intervals -- hard

Mum just came back from CHN.
take too much time. but it's time to back to work.

也是hard的一道题。FB的hard题真蛮多的,不过真的是很好的题,应该会再刷几遍的。从richardo92那里翻到了答案。

/**
 * 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 {
    public List merge(List intervals) {
        List ans = new ArrayList<>();
        if(intervals == null || intervals.size() == 0)  return ans;
        
        ans.add(intervals.get(0));
        for (int i=0; i=0; j--) {
                Interval prev = ans.get(j);
                if (prev.end < curr.start) {
                    ans.add(j+1, curr);
                    break;
                }
                else if (prev.start <= curr.start) {
                    prev.end = Math.max(prev.end, curr.end);
                    break;
                }
                else if (prev.start <= curr.end) {
                    prev.start = curr.start;
                    prev.end = Math.max(prev.end, curr.end);
                    curr = prev;
                    ans.remove(j);
                }
                else {
                    continue;
                }
            }
            if(j<0)   ans.add(0, curr);
        }
        return ans;
    }
}

你可能感兴趣的:(* 56. Merge Intervals -- hard)