[LeetCode] Largest Number

179. Largest Number

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool compare(const string& a, const string& b) {
return a + b < b + a;
}

class Solution {
public:
string largestNumber(vector<int>& nums) {
priority_queue<string, vector<string>, std::function<bool(string, string)>> pq(compare);
stringstream res;

for(auto num : nums)
pq.push(to_string(num));

while(!pq.empty()) {
res<<pq.top();
pq.pop();
}

return res.get() == '0' ? "0" : res.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/31/PS/LeetCode/largest-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.