-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert_intervals2.php
More file actions
41 lines (34 loc) · 984 Bytes
/
insert_intervals2.php
File metadata and controls
41 lines (34 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
class Solution
{
/**
* @param Integer[][] $intervals
* @param Integer[] $newInterval
* @return Integer[][]
*/
public function insert($intervals, $newInterval)
{
$start = 0;
$end = 0;
$n = count($intervals);
while ($end < $n) {
if ($newInterval[0] <= $intervals[$end][1]) {
if ($newInterval[1] < $intervals[$end][0]) {
break;
}
$newInterval[0] = min($newInterval[0], $intervals[$end][0]);
$newInterval[1] = max($newInterval[1], $intervals[$end][1]);
} else {
$start++;
}
$end++;
}
return array_merge(array_slice($intervals, 0, $start), array($newInterval), array_slice($intervals, $end));
}
}
$obj = new Solution();
$intervals = [[1, 5]];
$newInterval = [2, 3];
echo "<pre>";
print_r($obj->insert($intervals, $newInterval));
echo "</pre>";