179. Largest Number
To get a largest number, we can convert the numbers to strings and sort these strings in descending order. But when two strings have the same beginning, here comes a problem. For example, "30"
and "3"
have the same beginning, when we sort them in descending order, the concatenation of "30" + "3"
is "303"
, which is smaller than "3" + "30" = "330"
.
Thus when we customized a comparator, it won’t follow the simple descending order but compares two of the concatenations of the strings.
class Solution {
public String largestNumber(int[] nums) {
String[] numStrs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
numStrs[i] = String.valueOf(nums[i]);
}
Arrays.sort(numStrs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String order1 = o1 + o2;
String order2 = o2 + o1;
return order2.compareTo(order1);
}
});
if (numStrs[0].charAt(0) == '0') {
return "0";
}
StringBuilder builder = new StringBuilder();
for (String str : numStrs) {
builder.append(str);
}
return builder.toString();
}
}