|
| 1 | +/** |
| 2 | + * Definition for an interval. |
| 3 | + * class Interval { |
| 4 | + * public $start = 0; |
| 5 | + * public $end = 0; |
| 6 | + * function __construct(int $start = 0, int $end = 0) { |
| 7 | + * $this->start = $start; |
| 8 | + * $this->end = $end; |
| 9 | + * } |
| 10 | + * } |
| 11 | + */ |
| 12 | +class Solution { |
| 13 | + |
| 14 | + /** |
| 15 | + * @param Interval[] $intervals |
| 16 | + * @param Interval $newInterval |
| 17 | + * @return Interval[] |
| 18 | + */ |
| 19 | + function insert($intervals, $newInterval) { |
| 20 | + $res = []; |
| 21 | + |
| 22 | + $s = $newInterval->start; |
| 23 | + $e = $newInterval->end; |
| 24 | + |
| 25 | + foreach($intervals as $i) { |
| 26 | + if($i->start > $e) { |
| 27 | + array_push($res, new Interval($s,$e)); |
| 28 | + $s = $i->start; |
| 29 | + $e = $i->end; |
| 30 | + } |
| 31 | + |
| 32 | + if($s <= $i->end) { |
| 33 | + $s = min($s, $i->start); |
| 34 | + $e = max($e, $i->end); |
| 35 | + } |
| 36 | + else { |
| 37 | + array_push($res, $i); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + array_push($res, new Interval($s,$e)); |
| 42 | + return $res; |
| 43 | + } |
| 44 | +} |
0 commit comments