题目:
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程①:
快排版
源自LeetCode用户奶嘴超人丶
class Solution {
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
}
quickSort(strs, 0, strs.length - 1);
StringBuilder res = new StringBuilder();
for (String s : strs)
res.append(s);
return res.toString();
}
public void quickSort(String[] strs, int low, int high) {
if (low < high) {
int middle = getMiddle(strs, low, high);
quickSort(strs, low, middle - 1);
quickSort(strs, middle + 1, high);
}
}
public int getMiddle(String[] strs, int low, int high) {
//数组的第一个数为基准元素
String temp = strs[low];
while (low < high) {
//从后向前找比基准小的数
while (low < high && (strs[high] + temp).compareTo(temp + strs[high]) >= 0)
high--;
//把比基准小的数移到低端
strs[low] = strs[high];
//从前向后找比基准大的数
while (low < high && (strs[low] + temp).compareTo(temp + strs[low]) <= 0)
low++;
//把比基准大的数移到高端
strs[high] = strs[low];
}
strs[low] = temp;
return low;
}
}
执行结果①:

解题过程②:
内置函数:
需定义排序规则:
Java 定义为 (x, y) -> (x + y).compareTo(y + x) ;
class Solution {
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i = 0; i < nums.length; i++)
strs[i] = String.valueOf(nums[i]);
Arrays.sort(strs, (x, y) -> (x + y).compareTo(y + x));
StringBuilder res = new StringBuilder();
for(String s : strs)
res.append(s);
return res.toString();
}
}
作者:jyd
链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/solution/mian-shi-ti-45-ba-shu-zu-pai-cheng-zui-xiao-de-s-4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
执行结果②:

本文探讨了两种方法解决LeetCode问题,如何将非负整数数组拼接成最小数:一种是使用快速排序算法,另一种是借助Java内置排序函数。两种解法对比分析,展示了不同的实现思路和效率特点。
1022

被折叠的 条评论
为什么被折叠?



