-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFindTheDuplicateNumber.php
70 lines (59 loc) · 1.55 KB
/
FindTheDuplicateNumber.php
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
declare(strict_types=1);
namespace leetcode;
class FindTheDuplicateNumber
{
public static function findDuplicate(array $nums): int
{
if (empty($nums)) {
return 0;
}
$map = array_count_values($nums);
return array_search(max($map), $map, true);
}
public static function findDuplicate2(array $nums): int
{
if (empty($nums)) {
return 0;
}
$map = [];
foreach ($nums as $num) {
$map[$num] = ($map[$num] ?? 0) + 1;
}
return array_search(max($map), $map, true);
}
public static function findDuplicate3(array $nums): int
{
if (empty($nums)) {
return 0;
}
[$low, $high] = [$nums[0], count($nums) - 1];
while ($low < $high) {
[$cnt, $mid] = [0, $low + (int)(($high - $low) / 2)];
foreach ($nums as $num) {
if ($num <= $mid) {
$cnt++;
}
}
$cnt <= $mid ? ($low = $mid + 1) : ($high = $mid);
}
return $low;
}
public static function findDuplicate4(array $nums): int
{
if (empty($nums)) {
return 0;
}
[$slow, $fast] = [$nums[0], $nums[$nums[0]]];
while ($slow !== $fast) {
$slow = $nums[$slow];
$fast = $nums[$nums[$fast]];
}
$fast = 0;
while ($slow !== $fast) {
$fast = $nums[$fast];
$slow = $nums[$slow];
}
return $slow;
}
}