0
点赞
收藏
分享

微信扫一扫

LeetCode-179. Largest Number

半秋L 2022-08-10 阅读 68


Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]

Output: "210"

Example 2:

Input: [3,30,34,5,9]

Output: "9534330"

Note: The result may be very large, so you need to return a string instead of an integer.

题解:

自己写一个比较函数就行了,0值处理有点坑。

class Solution {
public:
//当sa + sb比sb + sa大时,判断a顺序在b之前,即true,反之则false
//这里的bool理解为a, b顺序关系,true为a在b之前,false为a在b之后
static bool cmp(int a, int b) {
string sa = to_string(a);
string sb = to_string(b);
if (sa + sb > sb + sa) {
return true;
}
else {
return false;
}
return true;
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), cmp);
string res;
for (int i = 0; i < nums.size(); i++) {
res += to_string(nums[i]);
}
while (res[0] == '0' && res.length() > 1) {
res.erase(0, 1);
}
return res;
}
};

 

举报

相关推荐

0 条评论