zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    Aspose.word总结
    表格样式
    Aspose.Words 总结
    mysql主从复制
    WebApi系列~通过HttpClient来调用Web Api接口
    Memcached服务器安装、配置、使用详解
    Jqery之select操作
    Centos7 设置IPtables
    memcached全面剖析--5
    memcached全面剖析--4
  • 原文地址:https://www.cnblogs.com/willwuss/p/12253466.html
Copyright © 2011-2022 走看看