[Sword refers to offer] 45. Arrange the array into the smallest number

Title description

Insert picture description here

Insert picture description here

// 45. 把数组排成最小的数

// 力扣
// 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,
// 打印能拼接出的所有数字中最小的一个。


// 牛客
// 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印
// 能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则
// 打印出这三个数字能排成的最小数字为321323。

answer

// 力扣
// 执行用时:6 ms, 在所有 Java 提交中击败了77.89%的用户
// 内存消耗:38 MB, 在所有 Java 提交中击败了60.99%的用户
import java.util.Arrays;
class Solution {
    public String minNumber(int[] nums) {
		if (nums == null || nums.length == 0)
			return "";
		int len = nums.length;  // 取数组nums的长度,即为字符组的长度
		String res = "";  // 答案存储在res中
		String[] strlist = new String[len];  // 创建与nums同尺寸的String list
		for (int i = 0; i < len; i++)
			strlist[i] = Integer.toString(nums[i]);  // 转字符串后排入String list
		// 给字符组list排序,lambda表达式来自定义比较器。
		// 原本是比较字符组每一个元素(字母)的大小来升序,
		// 现在是比较字符组每一个元素加起来组成的字符的大小来升序
		Arrays.sort(strlist, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
		// 排序后,将list所有元素按顺序存入res
		for (String s : strlist)
			res += s;
		return res;  // 最后返回res
    }
}


// 牛客
// 运行时间:100ms
// 占用内存:15052KB
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
    public String PrintMinNumber(int [] numbers) {
        if (numbers == null || numbers.length == 0)
            return "";
        String res = "";
        int len = numbers.length;
        String[] strList = new String[len];
        for (int i = 0; i < len; i++)
            strList[i] = Integer.toString(numbers[i]);
        Arrays.sort(strList, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
        for (String s: strList)
            res += s;
        return res;
    }
}


// 牛客
// 比较器修改的另一种写法
// 运行时间:14ms
// 占用内存:9988KB
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class Solution {
    public String PrintMinNumber(int [] numbers) {
        if (numbers == null || numbers.length == 0)
            return "";
        String res = "";
        int len = numbers.length;
        String[] strList = new String[len];
        for (int i = 0; i < len; i++)
            strList[i] = Integer.toString(numbers[i]);
        Arrays.sort(strList, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return (s1 + s2).compareTo(s2 + s1);
            }
        });
        for (String s: strList)
            res += s;
        return res;
    }
}

Guess you like

Origin blog.csdn.net/fisherish/article/details/113405014