Jerry's Blog

Recording what I learned everyday

View on GitHub


2 August 2020

LeetCode(56) -- Merge Intervals

by Jerry Zhang

Problem

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Solution

class Solution {
    private class IntervalComparator implements Comparator<int[]> {
        public int compare(int[] a, int[] b) {
            return a[0] < b[0] ? -1 : a[0] == b[0] ? 0 : 1;
        }
    }
    public int[][] merge(int[][] intervals) {
        Collections.sort(Arrays.asList(intervals), new IntervalComparator());
        LinkedList<int[]> merged = new LinkedList<>();
        for (int[] interval : intervals) {
            if (merged.isEmpty() || merged.getLast()[1] < interval[0]) {
                merged.add(interval);
            } else {
                merged.getLast()[1] = Math.max(merged.getLast()[1], interval[1]);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
}

The Best Solution

class Solution {
    public int[][] merge(int[][] intervals) {
        int count = intervals.length;    
        for(int i = 0; i < intervals.length - 1; ++i) {
            int[] i1 = intervals[i];
            for(int j = i + 1; j < intervals.length; ++j) {
                int[] i2 = intervals[j];
                if(i1[0] <= i2[1] && i1[1] >= i2[0]) {
                    i2[0] = Math.min(i1[0], i2[0]);
                    i2[1] = Math.max(i1[1], i2[1]);
                    i1[0] = 1;
                    i1[1] = 0;
                    --count;
                    break;
                }
            }
        }
        
        int[][] ans = new int[count][];
        for(int i = 0, j = 0; i < intervals.length; ++i) {
            if(intervals[i][0] <= intervals[i][1]) {
                ans[j++] = intervals[i];
            }
        }
        return ans;
    }
}

This 0ms solution is actually O(n^2), not better than the standard solution.

tags: LeetCode