File tree Expand file tree Collapse file tree 1 file changed +13
-11
lines changed Expand file tree Collapse file tree 1 file changed +13
-11
lines changed Original file line number Diff line number Diff line change @@ -2,27 +2,29 @@ class Solution {
2
2
public:
3
3
string largestNumber (vector<int >& nums)
4
4
{
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
+ }
6
11
7
12
// 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)
9
14
{
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));
16
17
});
17
18
18
19
// 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 " )
20
21
return " 0" ;
21
22
22
23
// form result string
23
- for (const auto & num : nums)
24
+ string largestNum;
25
+ for (const auto & num : numsStr)
24
26
{
25
- largestNum.append (to_string ( num) );
27
+ largestNum.append (num);
26
28
}
27
29
28
30
return largestNum;
You can’t perform that action at this time.
0 commit comments