topic link
Niuke.com online oj question - arrange the array into the smallest number
topic description
Input a non-negative integer array numbers, concatenate all the numbers in the array to form a number, and print the smallest one among all the numbers that can be concatenated.
For example, input the array [3, 32, 321], then print out that the smallest number that these three numbers can form is 321323.
1. The output result may be very large, so you need to return a string instead of an integer
2. The concatenated numbers may have leading 0, and the final result does not need to remove the leading 0
Data range:
0<=len(numbers)<=100
Topic example
Example 1
Input:
[11,3]
Return value:
"113"
Example 2
input:
[]
return value:
""
Example 3
Input:
[3,32,321]
Return value:
"321323"
problem solving ideas
The actual meaning of this question is: splicing all the elements in the array into a string, when the number corresponding to this string is smaller than other cases, what is the corresponding splicing order
First, all the elements in the array are added to the sequence table of the integer type, so that they can be sorted by the sort method in Collections
Collections.sort needs to pass in the sequence table list and comparison method, create a Comparator comparator, and rewrite the compare method in it
Among them, the o1 element is the first element, and the o2 element is the second element. Compare the number formed by o1o2 sorting and the number formed by o2o1 sorting respectively, and return the smaller value
Finally, create a stringBuffer object, and add the sorted sequence table to the stringBuffer object one by one to get the final string
full code
import java.util.*;
public class Solution {
public String PrintMinNumber(int [] numbers) {
if(numbers == null || numbers.length == 0){
return "";
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < numbers.length; i++){
list.add(numbers[i]);
}
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
String xs = x + "" + y;
String ys = y + "" + x;
return xs.compareTo(ys);
}
});
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < numbers.length; i++){
stringBuffer.append(list.get(i));
}
return stringBuffer.toString();
}
}