# 【LeetCode】Merge Intervals

## 题目

```Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].```

## 分析

### 自定义比较类

```     //      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;
}
}

public static final Comparator<Interval> BY_START = new ByStart();

private static class ByStart implements Comparator<Interval> {
@Override
public int compare(Interval o1, Interval o2) {
return o1.start - o2.start;
}
}```

### 主方法

```        public List<Interval> merge(List<Interval> intervals) {
ArrayList<Interval> result = new ArrayList<Interval>();

if (intervals == null || intervals.size() == 0) {
return result;
}

//按Interval的start对intervals排序
Collections.sort(intervals, BY_START);

Interval last = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
Interval temp = intervals.get(i);
if (canMerge(last, temp)) {
if (last.end <= temp.end) {
last = new Interval(last.start, temp.end);
}
//另外一种情况last保持不变
} else {
last = intervals.get(i);
}

}
return result;
}

private boolean canMerge(Interval item1, Interval item2) {
if (item1.end >= item2.start) {
return true;
}
return false;
}```

43 篇文章26 人订阅

0 条评论

## 相关文章

### ehcache报错

jfinal2.0+tomcat7+ehcache2.6.11+Linux Linux version 2.6.18-164.el5 (mockbuild@x8...

3759

2608

### 高通msm8909耳机调试

1、DTS相应修改： DTS相关代码：kernel/arch/arm/boot/dts/qcom/msm8909-qrd-skuc.dtsi： 1 s...

8175

### Html5模拟通讯录人员排序（sen.js）

// JavaScript Document  var PY_Json_Str = ""; var PY_Str_1 = ""; var PY_Str_...

6436

2782

941

### 高通Audio中ASOC的machine驱动

ASoC被分为Machine、Platform和Codec三大部分，其中的Machine驱动负责Platform和Codec之间的耦合以及部分和设备或板子特定的...

1K4

### Knapsack problem algorithms for my real-life carry-on knapsack

I'm a nomad and live out of one carry-on bag. This means that the total weight o...

1192

### java.base.jmod

/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/jmods\$ jmod list java....

1182

### App Guide相关

##TourGuide https://github.com/worker8/TourGuide

832