-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert-interval.php
More file actions
39 lines (34 loc) · 985 Bytes
/
insert-interval.php
File metadata and controls
39 lines (34 loc) · 985 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
<?php
class Solution
{
public function insert($intervals, $newInterval)
{
$start = 0;
$end = 0;
$n = count($intervals) - 1;
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 += 1;
}
$end += 1;
}
$zz = array_merge(array_slice($intervals, 0, $start), [$newInterval], array_slice($intervals, $end));
return $zz;
}
}
$obj = new Solution();
$intervals[] = [1, 2];
$intervals[] = [3, 5];
$intervals[] = [6, 7];
$intervals[] = [8, 10];
$intervals[] = [12, 16];
$newInterval = [4, 8];
echo "<pre>";
print_r($obj->insert($intervals, $newInterval));
echo "</pre>";