Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is
9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
sort the number first.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool myCompare(const int& a, const int& b) {
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
}
string largestNumber(vector<int>& nums) {
if(nums.size() == 0) return "";
sort(nums.begin(), nums.end(), myCompare);
string tmp = to_string(nums[0]);
for(int i = 1; i < nums.size(); ++i) {
tmp += to_string(nums[i]);
}
return tmp;
}
int main(void) {
vector<int> nums{0, 9, 8, 7, 6, 5, 4, 3, 2, 1};
string tmp = largestNumber(nums);
cout << tmp << endl;
}
本文介绍了一种算法,该算法接收一个非负整数列表,并通过重新排列这些整数来形成可能的最大数值。文章提供了完整的C++代码实现,包括自定义排序比较逻辑及最终字符串的构建过程。
857

被折叠的 条评论
为什么被折叠?



