maximum number
Problem description: Given a set of non-negative integers
nums
, rearrange the order of each number (each number is not splittable) to form the largest integer.Note: The output can be very large, so you need to return a string instead of an integer.
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/largest-number/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Array sorting
First, sort the given nums by sorting. The sorting logic is implemented by a comparator, which is to compare the forward connection and reverse connection of 2 numbers which is larger, and then connect the sorted arrays in order. .
Remarks: The logic is relatively clear, but the submission is successful after several submissions, mainly encountering the following two problems:
- I didn't consider the case of very large numbers, and the use of Integer led to out-of-bounds, so it is correct to change it to Long;
- The 0 of the prefix of the number after splicing is not considered meaningless and needs to be removed.
These two points are very basic, pay attention later.
import java.util.Arrays;
public class LeetCode_179 {
public static String largestNumber(int[] nums) {
String[] numsStr = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
numsStr[i] = String.valueOf(nums[i]);
}
Arrays.sort(numsStr, (o1, o2) -> {
if (Long.valueOf(o1 + o2) > Long.valueOf(o2 + o1)) {
return 1;
} else if (Long.valueOf(o1 + o2) < Long.valueOf(o2 + o1)) {
return -1;
} else {
return 0;
}
});
StringBuilder result = new StringBuilder();
for (int i = numsStr.length - 1; i >= 0; i--) {
result.append(numsStr[i]);
}
// 找到第一个不为0的数字
int index = 0;
for (char c : result.toString().toCharArray()) {
if (c != '0') {
break;
}
index++;
}
return index == result.length() ? "0" : result.substring(index);
}
public static void main(String[] args) {
int[] nums = new int[]{10, 2};
// 测试用例1,期望输出: 210
System.out.println(largestNumber(nums));
int[] nums2 = new int[]{3, 30, 34, 5, 9};
// 测试用例2,期望输出: 9534330
System.out.println(largestNumber(nums2));
int[] nums3 = new int[]{999999991, 9};
// 测试用例3,期望输出: 9999999991
// 考虑越界问题
System.out.println(largestNumber(nums3));
int[] nums4 = new int[]{0, 0};
// 测试用例4,期望输出: 0
// 考虑结果中的前缀0
System.out.println(largestNumber(nums4));
}
}
[Daily Message] If you don't break out in silence, you will perish in silence.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。