Test Failed
Push — master ( 3c1b4c...35db9d )
by Jinyun
03:48
created

LargestNumber::compare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class LargestNumber
8
{
9
    public static function largestNumber(array $nums): string
10
    {
11
        if (empty($nums)) {
12
            return '';
13
        }
14
        for ($i = 0, $n = count($nums); $i < $n; $i++) {
15
            for ($j = 0; $j < $n - $i - 1; $j++) {
16
                if (self::compare($nums[$j], $nums[$j + 1]) < 0) {
17
                    [$nums[$j], $nums[$j + 1]] = [$nums[$j + 1], $nums[$j]];
18
                }
19
            }
20
        }
21
        if ((int)$nums[0] === 0) {
22
            return '0';
23
        }
24
25
        return (string)join('', $nums);
26
    }
27
28
    public static function largestNumber2(array $nums): string
29
    {
30
        if (empty($nums)) {
31
            return '';
32
        }
33
        usort($nums, static function ($a, $b) {
34
            return -(($a.$b) <=> ($b.$a));
35
        });
36
        if ((int)$nums[0] === 0) {
37
            return '0';
38
        }
39
40
        return (string)implode('', $nums);
41
    }
42
43
    private static function compare(int $a, int $b): int
44
    {
45
        return ($a.$b) <=> ($b.$a);
46
    }
47
}
48