Skip to content

Commit 81862a2

Browse files
committed
Leetcode 57
1 parent 14e57eb commit 81862a2

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

51-100/57.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
## :pencil2:Leetcode基础刷题之(57. Insert Interval)
3+
<br>.
4+
**2020-02-11 吴亲库里 库里的深夜食堂**
5+
6+
### :pencil2:题目描述
7+
**在给定的一组不重叠的区间中,插入一个新的区间(必要时需要合并区间)。**
8+
****
9+
10+
### :pencil2:题目实例
11+
<a href="https://github.com/wuqinqiang/">
12+
​ <img src="https://github.com/wuqinqiang/Lettcode-php/blob/master/images/57.png">
13+
</a>
14+
****
15+
16+
****
17+
### :pencil2:题目分析
18+
**可以先看看两个 demo 中的案例。我们可以对原区间进行遍历,只有两种情况,要么加上 newInterval 区间后重叠了,要么不重叠,如果不重叠就好处理了,即在对应的区间位置加入一个未重叠的新区间。如果重叠了,因为可能包含了好几个重叠的区间,那就需要确定重叠的总区间,然后取相应的最小值和最大值组成新的区间。具体看代码**
19+
20+
### :pencil2:最终实现代码
21+
22+
```php
23+
24+
/**
25+
* @param Integer[][] $intervals
26+
* @param Integer[] $newInterval
27+
* @return Integer[][]
28+
*/
29+
function insert($intervals, $newInterval) {
30+
$res=[]; //最后结果
31+
$n=count($intervals);
32+
$cur=0; //记录位置
33+
34+
//未重叠
35+
while($cur<$n && $intervals[$cur][1]<$newInterval[0]){
36+
$res[]=$intervals[$cur++];
37+
}
38+
while($cur<$n && $intervals[$cur][0] <=$newInterval[1]){
39+
$newInterval[0]=min($intervals[$cur][0],$newInterval[0]);
40+
$newInterval[1]=max($intervals[$cur][1],$newInterval[1]);
41+
++$cur;
42+
}
43+
$res[]=$newInterval;
44+
//补上后面的区间
45+
while($cur<$n){
46+
$res[]=$intervals[$cur++];
47+
}
48+
return $res;
49+
}
50+
```
51+
52+
****
53+
### 联系
54+
55+
<a href="https://github.com/wuqinqiang/">
56+
​ <img src="https://github.com/wuqinqiang/Lettcode-php/blob/master/qrcode_for_gh_c194f9d4cdb1_430.jpg" width="150px" height="150px">
57+
</a>

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
- [Leetcode54](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/54.md)
7373
- [Leetcode55](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/55.md)
7474
- [Leetcode56](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/56.md)
75+
- [Leetcode57](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/57.md)
7576
- [Leetcode59](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/59.md)
7677
- [Leetcode61](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/61.md)
7778
- [Leetcode62](https://github.com/wuqinqiang/Lettcode-php/blob/master/51-100/62.md)

images/57.png

168 KB
Loading

0 commit comments

Comments
 (0)