Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 897141e

Browse files
committed
Add solution 56.
1 parent 5aa221b commit 897141e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
function cmp($a, $b) {
15+
if ($a->start == $b->start) {
16+
return 0;
17+
}
18+
return ($a->start < $b->start) ? -1 : 1;
19+
}
20+
21+
/**
22+
* @param Interval[] $intervals
23+
* @return Interval[]
24+
*/
25+
function merge($intervals) {
26+
usort($intervals, 'self::cmp');
27+
$mergedIntervals = [];
28+
29+
for ($i = 0; $i < count($intervals);) {
30+
$interval = $intervals[$i];
31+
$start = $interval->start;
32+
$end = $interval->end;
33+
34+
while (++$i < count($intervals) && $intervals[$i]->start <= $end) {
35+
if ($end < $intervals[$i]->end) {
36+
$end = $intervals[$i]->end;
37+
}
38+
}
39+
array_push($mergedIntervals, new Interval($start, $end));
40+
}
41+
42+
return $mergedIntervals;
43+
}
44+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /