# Leetcode 179: largest number

Leetcode 179: largest number

https://leetcode.com/problems/largest-number/

1, what is the largest number looks like?

2, how to make the arrangement in order to make the number large?
example:
1,2,5,34,36 –> 1243436, 5363421

3, the first idea is do the comparation carefully
1) find the largest highest digit in all numbers (may not find the final largest number) : 9123, 89, 77,
2) if there is two same largest digits, compare them and find the second largest digit in the two numbers
3) may use string comparation
String.sort()
Then I come up code like this:

public static String largestNumber(int[] nums) {
String[] a = new String[nums.length];
for (int i = 0; i < nums.length; ++i) {
a[i] = nums[i] + "";
}
Arrays.sort(a, Collections.reverseOrder());
String res = "";
for (String num : a) {
res += num;
}
return res;
}

4, when I finish the code, I found my solution cannot pass the test case: [121, 12]
1) there two possible arrangement: 12112, 12121
2) if we chose string comparation, the largest number should be 121, and the smaller would be 12
3) that means, if two numbers first few digits are same,
for example: 886,88,
we need to check other numbers in the nums[],
if there is 7x.. we need to chose 887x.. instead of 886..

5, So the custom comparation has some problems:
it need to compare the sum of the different arrangement of the two numbers:
for example: 121 and 12
we need to compare 12112 and 12121
Another exmaple: 98 and 999
we need to compare 98999 and 99998

6, the final code would be a little change:

public String largestNumber(int[] nums) {
String[] a = new String[nums.length];
for (int i = 0; i < nums.length; ++i) {
a[i] = nums[i] + "";
}
Arrays.sort(a,(str1,str2) -> (str2 + str1).compareTo(str1 + str2));
if(a[0].equals("0")) return "0";
String res = "";
for (String num : a) {
res += num;
}
return res;
}
• 本文已收录于以下专栏：

举报原因： 您举报文章：Leetcode 179: largest number 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)