LeetCode link

Intuition

  • Sort the numbers as strings in ascending order, the comparator is (s2 + s1).compareTo(s1 + s2)

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String largestNumber(int[] nums) {
if (nums.length < 1) {
return "";
}
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
}
Arrays.sort(strs, new Comparator<String>() {
public int compare(String s1, String s2) {
return (s2 + s1).compareTo(s1 + s2);
}
});
String result = "";
for (String str: strs) {
result += str;
}
return result;
}
}

problem

WA.

Input:
[0,0]
Output:
“00”
Expected:
“0”

reason

Miss the zero situation.


modification

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public String largestNumber(int[] nums) {
if (nums.length < 1) {
return "";
}
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
}
Arrays.sort(strs, new Comparator<String>() {
public int compare(String s1, String s2) {
return (s2 + s1).compareTo(s1 + s2);
}
});
if (strs[0].equals("0")) {
return "0";
}
String result = "";
for (String str: strs) {
result += str;
}
return result;
}
}