179 Largest Number

1. Question

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 is9534330.
Note: The result may be very large, so you need to return a string instead of an integer.

2. Implementation

(1) Sort
1
class Solution {
2
public String largestNumber(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return "";
5
}
6
7
int n = nums.length;
8
String[] strs = new String[n];
9
10
for (int i = 0; i < n; i++) {
11
strs[i] = nums[i] + "";
12
}
13
14
Arrays.sort(strs, (a, b)->((b + a).compareTo(a + b)));
15
16
if (strs[0].charAt(0) == '0') {
17
return "0";
18
}
19
20
StringBuilder res = new StringBuilder();
21
for (String str : strs) {
22
res.append(str);
23
}
24
return res.toString();
25
}
26
}
Copied!

3. Time & Space Complexity

时间复杂度O(nlogn), n是nums里的元素个数, 空间复杂度O(n)