Problem
Given a list of non-negative integers nums
, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example
Example 1:
|
|
Example 2:
|
|
Note: The result may be very large, so you need to return a string instead of an integer.
Solution
Method 1 - Using Sorting
This problem will be solved by greedy. We should put higher number before lower one. For eg. 9
before 5
OR 9
before 34
, as that will give us 95
and 934
respectively. Also, when we have same digit numbers like 35
and 34
, then 35
should come before 34
.
This problem can be solve by simply sorting strings, not sorting integer. Sorting integers will make 34 before 9, which will break our case.
Define a comparator to compare strings by concat() right-to-left or left-to-right.
|
|
Apparently, case1 is greater than case2 in terms of value.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
|
|