"Sword Finger Offer"-32, arrange the array into the smallest number

1. Knowledge points of this question

Array

2. 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.

3. Problem solving ideas

This question actually hopes that we can find a sorting rule, the array can be connected to the smallest number after rearranging according to this sorting rule. To determine such a sorting rule, that is, for two numbers m and n, a rule is used to determine which should be ranked first.

According to the requirements of the title, we can find that the two numbers m and n can be spliced ​​into mn and nm. If mn<nm, then m should be in front; if nm<mn, then n should be in front. Therefore, the sorting rules we get are as follows:

  • If mn>nm, then m is greater than n
  • If mn<nm, then m is less than n
  • If mn=nm, then m is equal to n

According to the above rules, we need to convert numbers into strings before comparing them, because they need to be spliced ​​together. After the comparison, connect them in order to form a string.

4. Code

public class Solution {
    
    
    public String PrintMinNumber(int[] numbers) {
    
    
        String result = "";
        String[] str = new String[numbers.length];
        // 将整数数组转换为字符串数组
        for (int i = 0; i < numbers.length; i++) {
    
    
            str[i] = String.valueOf(numbers[i]);
        }
        // 对字符串数组进行排序
        Arrays.sort(str, new Comparator<String>() {
    
    
            @Override
            public int compare(String m, String n) {
    
    
                String mn = m + n;
                String nm = n + m;
                return mn.compareTo(nm);
            }
        });
        // 最后拼接成一个字符串
        for (String s : str) {
    
    
            result += s;
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112968780