力扣(LeetCode)56

栏目: 编程工具 · 发布时间: 7年前

内容简介:题目地址:题目描述:

题目地址:

https://leetcode-cn.com/probl...

题目描述:

给出一个区间的集合,请合并所有重叠的区间。

示例 1:

输入: [[1,3],[2,6],[8,10],[15,18]]

输出: [[1,6],[8,10],[15,18]]

解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].

示例 2:

输入: [[1,4],[4,5]]

输出: [[1,5]]

解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。

解答:

按照区间起始节点排序。

然后合并即可,这题难的是怎么写出完美的合并代码。

判断逻辑是如果ans列表为空或者ans列表最后一个区间和当前区间不相交就加入当前区间。

否则把ans列表最后一个区间和当前区间合并。

java ac代码:

/**
 * 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 {
    public List<Interval> merge(List<Interval> intervals) {
        
        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                if(o1.start != o2.start)
                return o1.start-o2.start;
                return o1.end-o2.end;
            }
        });
        List<Interval> ans = new ArrayList(intervals.size());
        for(int i = 0;i < intervals.size();i++)
            if(ans.size() == 0||ans.get(ans.size()-1).end < intervals.get(i).start)
                ans.add(intervals.get(i));
        else
            ans.get(ans.size()-1).end =Math.max(intervals.get(i).end,ans.get(ans.size()-1).end    );
        return ans;
        
        
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Artificial Intelligence

Artificial Intelligence

Stuart Russell、Peter Norvig / Pearson / 2009-12-11 / USD 195.00

The long-anticipated revision of this #1 selling book offers the most comprehensive, state of the art introduction to the theory and practice of artificial intelligence for modern applications. Intell......一起来看看 《Artificial Intelligence》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具