Skip to content

Commit bac8d0c

Browse files
authored
Improved efficiency of largest number solution
1 parent 5659d9d commit bac8d0c

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

LargestNumber/solution.cpp

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,29 @@ class Solution {
22
public:
33
string largestNumber(vector<int>& nums)
44
{
5-
string largestNum;
5+
// convert nums to string ahead here once as they are needed as later to compare later as strings and append
6+
// converting here saves time converting multiple times in the sorting fn
7+
vector<string> numsStr;
8+
for (int num : nums) {
9+
numsStr.push_back(to_string(num));
10+
}
611

712
// use the exisiting sort algorithm with the modified condition fn below
8-
sort(nums.begin(), nums.end(), [ ](const int& num1, const int& num2)
13+
sort(numsStr.begin(), numsStr.end(), [ ](const auto& num1, const auto& num2)
914
{
10-
// return true if combo1 with num1 is "greater"
11-
12-
string combo1 = to_string(num1) + to_string(num2);
13-
string combo2 = to_string(num2) + to_string(num1);
14-
15-
return (combo1 > combo2);
15+
// return true if num1 is "greater"
16+
return ((num1 + num2) > (num2 + num1));
1617
});
1718

1819
// if 0 is considered the greatest num out of any potential other nums return 0 so no other chars are returned
19-
if (nums.front() == 0)
20+
if (numsStr.front() == "0")
2021
return "0";
2122

2223
// form result string
23-
for (const auto& num : nums)
24+
string largestNum;
25+
for (const auto& num : numsStr)
2426
{
25-
largestNum.append(to_string(num));
27+
largestNum.append(num);
2628
}
2729

2830
return largestNum;

0 commit comments

Comments
 (0)