Largest Number 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.
Example 1:
Input: nums = [10,2] Output: "210"
Example 2:
Input: nums = [3,30,34,5,9] Output: "9534330"
Constraints:
1 <= nums.length <= 100
Largest Number Solutions
✅Time: O(n log n)
✅Space: O(n)
C++
class Solution {
public:
string largestNumber(vector<int>& nums) {
string ans;
sort(begin(nums), end(nums), [](int a, int b) {
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
});
for (const int num : nums)
ans += to_string(num);
return ans[0] == '0' ? "0" : ans;
}
};
Java
class Solution {
public String largestNumber(int[] nums) {
final String s = Arrays.stream(nums)
.mapToObj(String::valueOf)
.sorted((a, b) -> (b + a).compareTo(a + b))
.collect(Collectors.joining(""));
return s.startsWith("00") ? "0" : s;
}
}
Python
class LargerStrKey(str):
def __lt__(x: str, y: str) -> bool:
return x + y > y + x
class Solution:
def largestNumber(self, nums: List[int]) -> str:
return ''.join(sorted(map(str, nums), key=LargerStrKey)).lstrip('0') or '0'
Watch Tutorial
Checkout more Solutions here