Problem Description
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Examples
Example 1: Input: nums = [10,2] Output: "210" Example 2: Input: nums = [3,30,34,5,9] Output: "9534330"
Python Solution
class Solution:
def largestNumber(self, nums: List[int]) -> str:
# Convert to strings for comparison
nums = [str(num) for num in nums]
# Custom comparison
def compare(n1: str, n2: str) -> int:
if n1 + n2 > n2 + n1:
return -1
return 1
# Sort using custom comparison
nums.sort(key=functools.cmp_to_key(compare))
# Handle case with all zeros
if nums[0] == '0':
return '0'
return ''.join(nums)
Java Solution
class Solution {
public String largestNumber(int[] nums) {
// Convert to strings
String[] asStrs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
asStrs[i] = String.valueOf(nums[i]);
}
// Sort using custom comparator
Arrays.sort(asStrs, (a, b) -> (b + a).compareTo(a + b));
// Handle case with all zeros
if (asStrs[0].equals("0")) {
return "0";
}
// Join the strings
StringBuilder result = new StringBuilder();
for (String str : asStrs) {
result.append(str);
}
return result.toString();
}
}
C++ Solution
class Solution {
public:
string largestNumber(vector& nums) {
// Convert to strings
vector asStrs;
for (int num : nums) {
asStrs.push_back(to_string(num));
}
// Sort using custom comparator
sort(asStrs.begin(), asStrs.end(), [](string& a, string& b) {
return a + b > b + a;
});
// Handle case with all zeros
if (asStrs[0] == "0") {
return "0";
}
// Join the strings
string result;
for (string& str : asStrs) {
result += str;
}
return result;
}
};
JavaScript Solution
/**
* @param {number[]} nums
* @return {string}
*/
var largestNumber = function(nums) {
// Convert to strings
nums = nums.map(String);
// Sort using custom comparison
nums.sort((a, b) => (b + a).localeCompare(a + b));
// Handle case with all zeros
if (nums[0] === '0') {
return '0';
}
return nums.join('');
};
C# Solution
public class Solution {
public string LargestNumber(int[] nums) {
// Convert to strings
string[] asStrs = nums.Select(n => n.ToString()).ToArray();
// Sort using custom comparison
Array.Sort(asStrs, (a, b) => (b + a).CompareTo(a + b));
// Handle case with all zeros
if (asStrs[0] == "0") {
return "0";
}
return string.Concat(asStrs);
}
}
Complexity Analysis
- Time Complexity: O(n log n) where n is the length of nums (dominated by sorting)
- Space Complexity: O(n) to store the string array
Solution Explanation
This solution uses custom string comparison:
- Key concept:
- String comparison
- Custom sorting
- Concatenation comparison
- Algorithm steps:
- Convert to strings
- Define comparison
- Sort numbers
- Handle edge cases
Key points:
- String concatenation
- Handle leading zeros
- Custom comparator
- Edge cases