题目链接
法一(优先队列)
public String largestNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return "";
}
List<String> list = new LinkedList<>();
for (int num : nums) {
list.add(String.valueOf(num));
}
PriorityQueue<String> priorityQueue = new PriorityQueue<>((o1, o2) -> {
return (o2 + o1).compareTo(o1 + o2);
});
priorityQueue.addAll(list);
StringBuilder sb = new StringBuilder();
while (!priorityQueue.isEmpty()) {
sb.append(priorityQueue.remove());
}
if (sb.toString().charAt(0) == '0') {
return "0";
}
return sb.toString();
}
法二(排序)
public String largestNumber_2(int[] nums) {
if (nums == null || nums.length == 0) {
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>() {
@Override
public int compare(String o1, String o2) {
return (o2 + o1).compareTo(o1 + o2);
}
});
if (strs[0].charAt(0) == '0') {
return "0";
}
return String.join("", strs);
}
法三(排序 + 流式编程)
public String largestNumber_3(int[] nums) {
return Arrays.stream(nums)
.boxed()
.map(String::valueOf)
.sorted((o1, o2) -> (o2 + o1).compareTo(o1 + o2))
.reduce(String::concat)
.filter(s -> !s.startsWith("0"))
.orElse("0");
}
本地测试
lay.showTitle(179);
Solution179 sol179 = new Solution179();
int[] nums179 = new int[]{3, 30, 34, 5, 9};
System.out.println(Arrays.toString(nums179));
System.out.println(sol179.largestNumber(nums179));
System.out.println(sol179.largestNumber_2(nums179));
System.out.println(sol179.largestNumber_3(nums179));