179. Largest Number #565
-
Topics: Given a list of non-negative integers Since the result may be very large, so you need to return a string instead of an integer. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to compare numbers based on their concatenated results. For two numbers Approach:
Let's implement this solution in PHP: 179. Largest Number <?php
/**
* @param Integer[] $nums
* @return String
*/
function largestNumber($nums) {
// Custom comparison function for sorting
usort($nums, function($a, $b) {
$order1 = $a . $b;
$order2 = $b . $a;
return strcmp($order2, $order1); // Sort in descending order based on concatenation
});
// Join the sorted numbers into a single string
$result = implode('', $nums);
// Handle the case where the largest number is "0"
return $result[0] === '0' ? '0' : $result;
}
// Example usage:
$nums1 = [10, 2];
echo largestNumber($nums1); // Output: "210"
$nums2 = [3, 30, 34, 5, 9];
echo largestNumber($nums2); // Output: "9534330"
?> Explanation:
This solution handles the constraints efficiently and returns the largest possible number as a string. |
Beta Was this translation helpful? Give feedback.
We need to compare numbers based on their concatenated results. For two numbers
a
andb
, we compareab
(a concatenated with b) andba
(b concatenated with a), and decide the order based on which forms a larger number.Approach:
0
, then the result is"0"
, as all numbers must be zero.Let's implement this solution in PHP: 179. Largest Number