[Array] Arrange the array into the smallest number

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 aand bcan be obtained with both the fight aband ba, if ab < bait is asmaller, if ab > bait is bsmaller, otherwise a=b. Java implementation is very simple, using the Collections container sorting, rewriting Comparatorcan

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;
}

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/113770276