Problem
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
Note: The result may be very large, so you need to return a string instead of an integer.
Idea: After observing the array and the
returned result, here we need to think
for example, when given num1 = 5,
num2 = 34, why we put num1 before num2.
The answer is simple, that is because
num1 + num2 (534) > num2 + num1 (345).
Therefore, we need to first sort the
array such that each adjacent two
numbers (indicate them by n1 and n2,
and assume that n1 is before n2 in
the sorted array) satisfy the rule
that n1 + n2 > n2 + n1.
So we need to first rewrite the Comparator.
Code:
public class Solution {
class MyComparator implements Comparator<String> {
public int compare (String s1, String s2) {
String str1 = s1 + s2;
String str2 = s2 + s2;
return str2.compareTo(str1);
}
}
public String largestNumber(int[] num) {
String[] strArray = new String[num.length];
for (int i = 0; i < num.length; i++) {
strArray[i] = String.valueOf(num[i]);
}
Comparator<String> comparator = new MyComparator();
Arrays.sort(strArray, comparator);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < num.length; i++) {
sb.append(strArray[i]);
}
return sb.charAt(0) == '0' ? "0" : sb.toString();
}
}