Leetcode 56 Merge Intervals (合并间隔) (Sort)

Leetcode 56

题目描述

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.

代码

Java
class Solution {
    public int[][] merge(int[][] intervals) {
        if ( intervals.length < 2 ) return intervals;
        Arrays.sort(intervals, new Comparator<int[]>(){
            public int compare(int[] a, int[] b){
                return a[0]-b[0];
            }
        });
        List<int[]> list = new ArrayList<>();
        int[] dummy = intervals[0];
        list.add(dummy);
        for(int[] interval : intervals){
            if (interval[0] <= dummy[1]){
                dummy[1] = Math.max(interval[1], dummy[1]);
            }
            else {
                dummy = interval;
                list.add(dummy);
            }
        }
        return list.toArray(new int[list.size()][]);
        
    }
}
Python3
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        ans = []
        for interval in sorted(intervals, key = lambda x:x[0]):
            if not ans or interval[0] > ans[-1][1]:
                ans.append(interval)
            else :
                ans[-1][1] = max(ans[-1][1], interval[1])
        return ans
posted @ 2020-02-02 20:10  willwuss  阅读(121)  评论(0编辑  收藏  举报