Largest Number
Given a list of non-negative integers nums
Since the result may be very large, so you need to return a string instead of an integer.
Example 1
Output: "210"
Example 2
Output: "9534330"
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 109
Solution 1 - Sort input numbers using a custom comparator
In this approach, we are going to sort the numbers using a custom comparator, that is convert the input numbers into strings and compare them such that
it sorts based on the digits and not as a whole number, for example if these two numbers were given as input 3499
So, in the custom comparator, say num1num2num1+""+num2num2+""+num1
For example, in the input numbers given to comparator are num1 = 34num2 = 93499349
import java.util.stream.IntStream;
public class LargestNumber {
static String largestNumber(int[] nums) {
StringBuilder sb = new StringBuilder();
IntStream.of(nums).boxed().sorted((num1, num2)->{
String compare1 = num1+""+num2;
String compare2 = num2+""+num1;
return compare2.compareTo(compare1);
}).forEach(sb::append);
if(sb.charAt(0) == '0') {
return "0";
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(largestNumber(new int[]{3,30,34,5,9}));
System.out.println(largestNumber(new int[]{0, 0}));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n log n) time where nnums
Space complexity: O(1), assuming sort()
Above implementations source code can be found at