Skip to content

Commit c10d796

Browse files
committed
Update fixed-point solution
1 parent 4366d30 commit c10d796

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/leetcode/FixedPoint.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode;
6+
7+
class FixedPoint
8+
{
9+
public static function fixedPoint(array $nums): int
10+
{
11+
if (empty($nums)) {
12+
return 0;
13+
}
14+
15+
foreach ($nums as $key => $val) {
16+
if ($key === $val) {
17+
return $key;
18+
}
19+
}
20+
21+
return -1;
22+
}
23+
24+
public static function fixedPoint2(array $nums): int
25+
{
26+
if (empty($nums)) {
27+
return 0;
28+
}
29+
30+
[$low, $high] = [0, $nums[count($nums) - 1]];
31+
while ($low <= $high) {
32+
$mid = (int) ($low + ($high - $low) / 2);
33+
if ($nums[$mid] === $mid) {
34+
return $mid;
35+
} elseif ($mid > $nums[$mid]) {
36+
$low++;
37+
} else {
38+
$high--;
39+
}
40+
}
41+
42+
return -1;
43+
}
44+
}

tests/leetcode/FixedPointTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode\tests;
6+
7+
use leetcode\FixedPoint;
8+
use PHPUnit\Framework\TestCase;
9+
10+
class FixedPointTest extends TestCase
11+
{
12+
public function testFixedPoint(): void
13+
{
14+
self::assertSame(3, FixedPoint::fixedPoint([-10, -5, 0, 3, 7]));
15+
self::assertSame(-1, FixedPoint::fixedPoint([-10, -5, 3, 4, 7, 9]));
16+
}
17+
18+
public function testFixedPoint2(): void
19+
{
20+
self::assertSame(3, FixedPoint::fixedPoint2([-10, -5, 0, 3, 7]));
21+
self::assertSame(-1, FixedPoint::fixedPoint2([-10, -5, 3, 4, 7, 9]));
22+
}
23+
}

0 commit comments

Comments
 (0)