leetcode 179 largest number

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 is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. 思路:比较两个数连接后的大小进行排序。 Runtime: 125 ms  beats 88.37%

1
2
3
4
5
6
7
8
public static String (int[] nums) {
String[] s = new String[nums.length];
for (int i = 0; i < nums.length; i++) s[i] = String.valueOf(nums[i]);
Arrays.sort(s, (b, a) -> (a.concat(b).compareTo(b.concat(a))));
StringBuffer result = new StringBuffer("");
for (String num : s) result.append(num);
return result.substring(0, 1).equals("0") ? "0" : result.toString();
}

使用java8的特性: Runtime: 153 ms beats 10.23%

1
2
3
4
5
6
7
8
public String largestNumber2(int[] nums) {
String result = Arrays
.stream(nums)
.mapToObj(Integer::toString)
.sorted((b, a) -> (a.concat(b).compareTo(b.concat(a))))
.collect(Collectors.joining());
return result.charAt(0) == '0' ? "0" : result;
}