Title description
Input an array of positive integers, concatenate all the numbers in the array into one number, and print the smallest one of all the numbers that can be spliced together. For example, input the array {3, 32, 321}, and print out the smallest number that these three numbers can be arranged as 321323.
First convert each number into a string, and then sort the strings. The key is that you need to redefine the comparison function between the two strings when sorting. You can't compare in the simplest lexicographical order, because it outputs The result is not minimal.
For strings a
and b
can be obtained with both the fight ab
and ba
, if ab < ba
it is a
smaller, if ab > ba
it is b
smaller, otherwise a=b
. Java implementation is very simple, using the Collections container sorting, rewriting Comparator
can
public String PrintMinNumber(int[] numbers) {
ArrayList<Integer> nums = new ArrayList<>();
for (int v : numbers) nums.add(v);
Collections.sort(nums, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
String s1, s2;
s1 = "" + o1 + o2;
s2 = "" + o2 + o1;
return s1.compareTo(s2);
}
});
String str = "";
for (int v : nums) str += v;
return str;
}