Poison

179. Largest Number

Sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public String largestNumber(int[] nums) {
String[] numStrArray = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
numStrArray[i] = String.valueOf(nums[i]);
}

Arrays.sort(numStrArray, (o1, o2) -> (o2 + o1).compareTo(o1 + o2));
String res = String.join("", numStrArray);

// 注意处理多个前导 0 的情况,如 nums: [0, 0]
int firstNonZeroIndex = 0;
while (firstNonZeroIndex < res.length() - 1 && res.charAt(firstNonZeroIndex) == '0') {
firstNonZeroIndex++;
}
return res.substring(firstNonZeroIndex);
}
}
Sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public String largestNumber(int[] nums) {
List<Integer> numList = new ArrayList<>(nums.length);
for (int num : nums) {
numList.add(num);
}

numList.sort((x, y) -> {
// xy > yx
long product = 10;
while (product <= y) {
product *= 10;
}
long a = x * product + y;

product = 10;
while (product <= x) {
product *= 10;
}
long b = y * product + x;

return a == b ? 0 : (a - b > 0 ? -1 : 1); // 注意此处的顺序
});

StringBuilder sb = new StringBuilder();
for (int num : numList) {
sb.append(num);
}
String res = sb.toString();

// 注意处理多个前导 0 的情况,如 nums: [0, 0]
int firstNonZeroIndex = 0;
while (firstNonZeroIndex < res.length() - 1 && res.charAt(firstNonZeroIndex) == '0') {
firstNonZeroIndex++;
}
return res.substring(firstNonZeroIndex);
}
}
Reference

179. Largest Number