题目:合并区间

难度:Medium

题目内容

 

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]]

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]

我的思路:因为可能是乱序的,不好逐个比较,所以需要排序

1、将List内的元素进行排序(利用比较器),然后从前往后比较 ;

2、当前的end和后一个的start,看是否需要合并

3、如果需要合并则当前的end等于它自己与后一个的end中取大的,然后将后一个remove()掉

我的代码

 class Solution {
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new MyComparator()); for (int i = 0; i < intervals.size() - 1; i++) {
if (intervals.get(i).end >= intervals.get(i+1).start) {
intervals.get(i).end = intervals.get(i).end > intervals.get(i+1).end ? intervals.get(i).end : intervals.get(i+1).end;
intervals.remove(i+1);
i--;
}
}
return intervals;
}
} class MyComparator implements Comparator<Interval> { public int compare(Interval one, Interval two) {
return one.start - two.start;
} }

我的复杂度:O(NlogN)    主要是排序的那里用了nlogn    剩下的只有n

编程过程中的问题

1、忘记比较器怎么实现:

方法一:将List中的类实现Comparable<E>接口(本题的E就是Interval),并重写compareTo方法(一个传入对象)  用自己的值和传入对象的值做比较即可。

【比较规则:自己比传入对象大就返回零,等于就等于0,小于就小于0,所以一般直接   return   自己 - 传入对象】如下:

    public int compareTo(Interval o) {
return start - o.start;
}

但是,本题的Interval是写死的不能在编辑中修改,但是不要急,还有另外一种办法:

  方法二:自己写一个类实现Comparator<E>接口,并重写compare方法(两个传入对象)

【比较规则:与上面类似  一般直接 return   前面一个对象 - 后面一个对象】如下:

    public int compare(Interval one, Interval two) {
return one.start - two.start;
}

扩展:那如果要比较两个属性呢,比如先比较名字,再比较年龄————代码如下

    public int compare(Person one, Person two) {
int i = one.name.compareTo(two.name); //比较名字字符串
if (i == 0) { //如果名字一样,则继续比较年龄
return one.age - two.age;
} else { //首先比较名字,名字不一样,则返回比较结果
return i;
}
}

  使用此方法需要在sort()方法中传入作为第二个参数,(所以一般可直接在sort方法里使用匿名类)如下:

        Collections.sort(intervals, new Comparator<Interval>(){
@Override
public int compare(Interval interval1, Interval interval2){
return interval1.start - interval2.start;
}
});

2、发现需要合并后,是不能直接将end取后一个的end的,因为后一个的end也是有可能比当前的小的,比如【【1,6】,【3,5】】,所以需要判断一下end的大小;

3、因为是顺序向后循环的,List调用remove方法去掉后一个之后,i 会指向后一个继续进行循环,但是此时应该仍然指向自己,继续判断后一个是否需要合并,所以需要 i - -。

  扩展:如果是从后往前循环的呢?需要 i ++?

    此时删去了下标i - 1,然后 i -- ,i 移到 下标 i -1 , 而此时的下标 i -1 就是remove之前的 下标 i 所以不再需要做操作。

    例如:下标 0,1,2  此时 i 等于2 ,将1remove(此时的下标2自动变为1),然后 i -- ,i还是指向原来的2的位置。

  所以,当在循环中调用List的remove方法的时候,一定要考虑下标的变化,而调整指针 i 的值。

答案代码

 class Solution {
private class IntervalComparator implements Comparator<Interval> {
@Override
public int compare(Interval a, Interval b) {
return a.start < b.start ? -1 : a.start == b.start ? 0 : 1;
}
} public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new IntervalComparator()); LinkedList<Interval> merged = new LinkedList<Interval>();
for (Interval interval : intervals) {
if (merged.isEmpty() || merged.getLast().end < interval.start) {
merged.add(interval);
}
else {
merged.getLast().end = Math.max(merged.getLast().end, interval.end);
}
} return merged;
}
}

答案思路:和我的思路是一样的,先排序然后从头到位判断是否需要合并,

不过他使用了队列,空间复杂度提高了,但是这样避免了remove方法带来的多余的时间复杂度,二者各有好处。

LeetCode第[56]题(Java):Merge Intervals的更多相关文章

  1. 【LeetCode每天一题】Merge Intervals(合并区间)

    Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8, ...

  2. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  3. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  4. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  5. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  6. LeetCode解题报告—— Jump Game & Merge Intervals & Permutation Sequence

    1. Jump Game Given an array of non-negative integers, you are initially positioned at the first inde ...

  7. LeetCode第[88]题(Java):Merge Sorted Array(合并已排序数组)

    题目:合并已排序数组 难度:Easy 题目内容: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as ...

  8. 【Leetcode】【Hard】Merge Intervals

    Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,1 ...

  9. LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

随机推荐

  1. 高德js API moveAlong 函数的一个错误解决

    使用覆盖物之一:点标记,让点标记沿着固定的路线移动. API 提供了现成的函数 moveAlong() 开始以为 实现移动很简单:分两部 1.准备好经纬度数组 2.调用moveAlong()函数.按照 ...

  2. Twitter的RPC框架Finagle简介

    Twitter的RPC框架Finagle简介 http://www.infoq.com/cn/news/2014/05/twitter-finagle-intro

  3. Linux的进程/线程通信方式总结(转)

    Linux系统中的进程通信方式主要以下几种: 同一主机上的进程通信方式 * UNIX进程间通信方式: 包括管道(PIPE), 有名管道(FIFO), 和信号(Signal) * System V进程通 ...

  4. Vue.js——框架

    一.什么是VUE vue 是一个构建用户界面的javascript框架 特点:轻量,高效 特性:双向数据绑定,数据驱动视图 二.vue的使用 1.引入vue.js <script src=vue ...

  5. Python(面向对象编程4——继承顺序、封装)

    继承顺序 ''' 一点需要注意 ''' class Father: def f1(self): print("test func followed ==>") self.te ...

  6. delphi webbrowser post自动登录

    delphi webbrowser post自动登录     var  EncodedDataString: WideString;  PostData: OleVariant;  Headers: ...

  7. [笔记]Go语言写文件几种方式性能对比

    Go语言中写文件有多种方式,这里进行如下几种方式的速度对比: 打开文件,写入内容,关闭文件.如此重复多次 打开文件,写入内容,defer 关闭文件.如此重复多次 打开文件,重复多次写入内容,defer ...

  8. LightOJ - 1138 (二分+阶乘分解)

    题意:求阶乘尾部有Q(1 ≤ Q ≤ 108)个0的最小N 分析:如果给出N,然后求N!尾部0的个数的话,直接对N除5分解即可(因为尾部0肯定是由5*2构成,那么而在阶乘种,2的因子个数要比5少,所以 ...

  9. POJ 3463 Sightseeing (次短路)

    题意:求两点之间最短路的数目加上比最短路长度大1的路径数目 分析:可以转化为求最短路和次短路的问题,如果次短路比最短路大1,那么结果就是最短路数目加上次短路数目,否则就不加. 求解次短路的过程也是基于 ...

  10. python 课堂笔记-购物车

    # Author:leon production_list = [ ('iphone',5800), ('mac pro', 9800), ('bike', 800), ('watch', 10600 ...