Given a list of non-negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note:
The problem requires forming the largest number possible from concatenation of given numbers. The approach involves sorting the numbers based on a custom comparator:
a
and b
, check if ab
is greater than ba
).0
(e.g., [0, 0]
should return “0”).import java.util.*;
public class LargestNumber {
public String largestNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return "";
}
String[] asStrs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
asStrs[i] = String.valueOf(nums[i]);
}
Arrays.sort(asStrs, new Comparator<String>() {
@Override
public int compare(String a, String b) {
String order1 = a + b;
String order2 = b + a;
return order2.compareTo(order1);
}
});
// If the largest number is 0, the result is "0".
if (asStrs[0].equals("0")) {
return "0";
}
StringBuilder sb = new StringBuilder();
for (String numAsStr : asStrs) {
sb.append(numAsStr);
}
return sb.toString();
}
public static void main(String[] args) {
LargestNumber solution = new LargestNumber();
int[] nums1 = {10, 2};
int[] nums2 = {3, 30, 34, 5, 9};
System.out.println(solution.largestNumber(nums1)); // Output: "210"
System.out.println(solution.largestNumber(nums2)); // Output: "9534330"
}
}
Thus, the overall time complexity is (O(n \log n + nm)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?