1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | class FindTheDuplicateNumber |
||
8 | { |
||
9 | public static function findDuplicate(array $nums): int |
||
10 | { |
||
11 | if (empty($nums)) { |
||
12 | return 0; |
||
13 | } |
||
14 | $map = array_count_values($nums); |
||
15 | |||
16 | return array_search(max($map), $map, true); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
17 | } |
||
18 | |||
19 | public static function findDuplicate2(array $nums): int |
||
20 | { |
||
21 | if (empty($nums)) { |
||
22 | return 0; |
||
23 | } |
||
24 | $map = []; |
||
25 | foreach ($nums as $num) { |
||
26 | $map[$num] = ($map[$num] ?? 0) + 1; |
||
27 | } |
||
28 | |||
29 | return array_search(max($map), $map, true); |
||
0 ignored issues
–
show
|
|||
30 | } |
||
31 | |||
32 | public static function findDuplicate3(array $nums): int |
||
33 | { |
||
34 | if (empty($nums)) { |
||
35 | return 0; |
||
36 | } |
||
37 | [$low, $high] = [$nums[0], count($nums) - 1]; |
||
38 | while ($low < $high) { |
||
39 | [$cnt, $mid] = [0, $low + (int)(($high - $low) / 2)]; |
||
40 | foreach ($nums as $num) { |
||
41 | if ($num <= $mid) { |
||
42 | $cnt++; |
||
43 | } |
||
44 | } |
||
45 | $cnt <= $mid ? ($low = $mid + 1) : ($high = $mid); |
||
46 | } |
||
47 | |||
48 | return $low; |
||
49 | } |
||
50 | |||
51 | public static function findDuplicate4(array $nums): int |
||
52 | { |
||
53 | if (empty($nums)) { |
||
54 | return 0; |
||
55 | } |
||
56 | [$slow, $fast] = [$nums[0], $nums[$nums[0]]]; |
||
57 | while ($slow !== $fast) { |
||
58 | $slow = $nums[$slow]; |
||
59 | $fast = $nums[$nums[$fast]]; |
||
60 | } |
||
61 | |||
62 | $fast = 0; |
||
63 | while ($slow !== $fast) { |
||
64 | $fast = $nums[$fast]; |
||
65 | $slow = $nums[$slow]; |
||
66 | } |
||
67 | |||
68 | return $slow; |
||
69 | } |
||
70 | } |
||
71 |