179. Largest Number
Last updated
Last updated
the key is this:
Arrays.sort(str, (String s1, String s2) -> (s2+s1).compareTo(s1+s2));
sort input [3,30,34,5,9]
to [9, 5, 34, 3, 30]
ex: 34,3 -> 334, 343 compare which one is bigger
need to handle edge case for all zero : ["0", "0", "0"]
class Solution {
public String largestNumber(int[] nums) {
List<String> list = new ArrayList<>();
for (int num : nums) {
list.add(String.valueOf(num));
}
Collections.sort(list, (a, b) -> (b + a).compareTo(a + b));
// for "0", "0", "0" case
if (!list.isEmpty() && list.get(0).length() > 0 && list.get(0).charAt(0) == '0') {
return "0";
}
StringBuilder result = new StringBuilder();
for (String s : list) {
result.append(s);
}
return result.toString();
}
}
/**
compare first digits on the left first
if first digits is the same but len is different
330
303
32 30 3
33230
32330
32303
45 41 4
44341
45441
443 43 4
443434
444343
30 3
303 330
using a+b comapre to b+a!
*/
Time: O(nlogn)
space: O(n)
class Solution {
public String largestNumber(int[] nums) {
String str[] = new String[nums.length];
for (int i = 0; i < nums.length ; i++) {
str[i] = String.valueOf(nums[i]);
}
Arrays.sort(str, (String s1, String s2) -> (s2+s1).compareTo(s1+s2));
if (str[0].charAt(0) == '0') return "0"; //corner case
StringBuilder sb = new StringBuilder();
for (String s : str) {
sb.append(s);
}
return sb.toString();
}
}
```java
class Solution {
public String largestNumber(int[] nums) {
String[] str = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
str[i] = String.valueOf(nums[i]);
}
Arrays.sort(str, (a, b) -> (b+a).compareTo(a+b));
// so large one will in front of it
// so if the first one is 0, result is 0
// if (str[0].length() > 0 && str[0].charAt(0) == '0') {
// return "0";
// }
StringBuilder sb = new StringBuilder();
for (String s : str) {
sb.append(s);
}
return sb.charAt(0) == '0' ? "0" : sb.toString(); // or just check first one char is 0 or not
}
}
```