-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLargestNumber.php
47 lines (40 loc) · 1.06 KB
/
LargestNumber.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
<?php
declare(strict_types=1);
namespace leetcode;
class LargestNumber
{
public static function largestNumber(array $nums): string
{
if (empty($nums)) {
return '';
}
for ($i = 0, $n = count($nums); $i < $n; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if (self::compare($nums[$j], $nums[$j + 1]) < 0) {
[$nums[$j], $nums[$j + 1]] = [$nums[$j + 1], $nums[$j]];
}
}
}
if ((int)$nums[0] === 0) {
return '0';
}
return (string)join('', $nums);
}
public static function largestNumber2(array $nums): string
{
if (empty($nums)) {
return '';
}
usort($nums, static function ($a, $b) {
return -(($a . $b) <=> ($b . $a));
});
if ((int)$nums[0] === 0) {
return '0';
}
return (string)implode('', $nums);
}
private static function compare(int $a, int $b): int
{
return ($a . $b) <=> ($b . $a);
}
}