王廷瑋|數位醫療|智慧醫療: 179. Largest Number WFU

2024年7月10日 星期三

179. Largest Number

179. Largest Number


當給定一個非負整數組成的列表 nums 時,將它們排列成一個最大的數字並返回。

由於結果可能非常大,因此需要返回一個字串而不是整數。

範例 :

輸入: nums = [10,2] 輸出: "210"


Python


from typing import List

class Solution:
def largestNumber(self, nums: List[int]) -> str:
# Convert integers to strings to prepare for custom sorting
str_nums = list(map(str, nums))
# Custom comparator for sorting
str_nums.sort(key=lambda x: x*10, reverse=True)
# Join sorted strings
largest_num = ''.join(str_nums)
# Edge case: when the list contains only zeros
if largest_num[0] == '0':
return '0'
return largest_num

16.48MB, 37ms


C++


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class Solution {
public:
string largestNumber(vector<int>& nums) {
// Convert the numbers to strings
vector<string> strNums;
for (int num : nums) {
strNums.push_back(to_string(num));
}
// Custom comparator to sort the numbers in a way that forms the largest number
sort(strNums.begin(), strNums.end(), [](const string &a, const string &b) {
return a + b > b + a;
});
// Edge case: if the largest number is "0", return "0"
if (strNums[0] == "0") {
return "0";
}
// Join sorted strings to form the largest number
string largestNum;
for (const string &str : strNums) {
largestNum += str;
}
return largestNum;
}
};

17.54MB, 7ms


Javascript


/**
* @param {number[]} nums
* @return {string}
*/
var largestNumber = function(nums) {
// Convert the numbers to strings
let strNums = nums.map(num => num.toString());
// Custom comparator to sort the numbers in a way that forms the largest number
strNums.sort((a, b) => (b + a) - (a + b));
// Join sorted strings to form the largest number
let largestNum = strNums.join('');
// Edge case: if the largest number is "0", return "0"
if (largestNum[0] === '0') {
return '0';
}
return largestNum;
};

50.92MB, 57ms