-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path179_largest_number.cpp
More file actions
52 lines (41 loc) · 1.2 KB
/
Copy path179_largest_number.cpp
File metadata and controls
52 lines (41 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
// O(SNlogN)
class Solution {
public:
std::string largestNumber(const std::vector<int>& nums) {
if (nums.size() == 0)
return "";
// O(SN) space
std::vector<std::string> nums_str;
nums_str.reserve(nums.size());
for (int v : nums)
nums_str.push_back(std::to_string(v));
// O(S)
auto correct_order = [](std::string& l, std::string& r){return l + r > r + l;};
// O(SNlogN)
std::sort(nums_str.begin(), nums_str.end(), correct_order);
// O(SN) time
std::string longest = "";
for (std::string v : nums_str)
longest += v;
longest = longest.at(0) == '0' ? "0" : longest;
return longest;
}
};
int main(){
std::cout << "Space separated numbers: ";
std::string line;
std::getline(std::cin, line);
// split by space
std::vector<int> nums;
int c;
std::istringstream iss(line);
while (iss >> c) {
nums.push_back(c);
}
std::cout << "Largest number: " << Solution().largestNumber(nums) << std::endl;
return 0;
}