Skip to content

Commit a76292f

Browse files
committed
Add first-bad-version solution
1 parent 42679d2 commit a76292f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/leetcode/FirstBadVersion.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode;
6+
7+
class FirstBadVersion
8+
{
9+
public static function firstBadVersion(int $m, int $n): int
10+
{
11+
if ($m <= 0 || $n <= 0) {
12+
return 0;
13+
}
14+
[$low, $high] = [1, $m];
15+
while ($low <= $high) {
16+
$mid = $low + (int)(($high - $low) / 2);
17+
if (self::isBadVersion($mid, $n)) {
18+
$high = $mid - 1;
19+
} else {
20+
$low = $mid + 1;
21+
}
22+
}
23+
24+
return $low;
25+
}
26+
27+
public static function isBadVersion(int $m, int $n): bool
28+
{
29+
$map = array_fill(0, $n + 1, false);
30+
$map[$n] = true;
31+
32+
return $map[$m];
33+
}
34+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode\tests;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use leetcode\FirstBadVersion;
9+
10+
class FirstBadVersionTest extends TestCase
11+
{
12+
public function testFirstBadVersion(): void
13+
{
14+
self::assertSame(4, FirstBadVersion::firstBadVersion(5, 4));
15+
self::assertSame(1, FirstBadVersion::firstBadVersion(1, 1));
16+
}
17+
}

0 commit comments

Comments
 (0)