算法题 剑指Offer45 把数组排成最小的数
难度:中等
1. 题目
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例 1:
输入: [10,2]
输出: “102”
示例 2:
输入: [3,30,34,5,9]
输出: “3033459”
提示:
- 0 < nums.length <= 100
说明:
- 输出结果可能非常大,所以你需要返回一个字符串而不是整数
- 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0
Related Topics
贪心 | 字符串 | 排序
2. 解法
以下解法,参考于:https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/solutions/190476/mian-shi-ti-45-ba-shu-zu-pai-cheng-zui-xiao-de-s-4/
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]);
}
// 排序
this.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 mid = this.getMid(strs, low, high);
// 基准值左右两边,接着确定新基准值的位置
quickSort(strs, low, mid - 1);
quickSort(strs, mid + 1, high);
}
}
public int getMid(String[] strs, int low, int high) {
//数组的第一个数为基准元素
String tmp = strs[low];
while (low < high) {
//从后向前找比基准小的数
while (low < high && (strs[high] + tmp).compareTo(tmp + strs[high]) >= 0) high--;
//把比基准小的数移到低端
strs[low] = strs[high];
//从前向后找比基准大的数
while (low < high && (strs[low] + tmp).compareTo(tmp + strs[low]) <= 0) low++;
//把比基准大的数移到高端
strs[high] = strs[low];
}
// low==height时,返回基准值的正确位置
strs[low] = tmp;
return low;
}
}
3. 总结 (核心知识点)
-
字符串比较问题:String类型的compareTo方法
1.返回参与比较的前后两个字符串的asc码的差值,如果两个字符串首字母不同,则该方法返回首字母的asc码的差值
2.即参与比较的两个字符串如果首字符相同,则比较下一个字符,直到有不同的为止,返回该不同的字符的asc码差值,
3.如果两个字符串不一样长,可以参与比较的字符又完全一样,则返回两个字符串的长度差值注意:Integer、Date、BigDecimal等类型的compareTo方法与字符串的用法不同。
注: 测试用例:[10,2],测试结果:“102”。
所以需要拼接两个字符串后再比较(strs[high] + tmp).compareTo(tmp + strs[high])
,
而不能直接比较两个字符串(strs[high]).compareTo(tmp)
,否则"10"
中的"1"
比"2"
小,会导致("10")compareTo("2")
的值为-1
。
(参考第一条规则:两个字符串首字母不同,则该方法返回首字母的asc码的差值) -
快排模板
public void quickSort(String[] strs, int low, int high) { if (low < high) { // 确定基准值正确位置 int mid = this.getMid(strs, low, high); // 基准值左右两边,接着确定新基准值的位置 quickSort(strs, low, mid - 1); quickSort(strs, mid + 1, high); } } public int getMid(String[] strs, int low, int high) { //数组的第一个数为基准元素 String tmp = strs[low]; while (low < high) { //从后向前找比基准小的数 while (low < high && (strs[high] + tmp).compareTo(tmp + strs[high]) >= 0) high--; //把比基准小的数移到低端 strs[low] = strs[high]; //从前向后找比基准大的数 while (low < high && (strs[low] + tmp).compareTo(tmp + strs[low]) <= 0) low++; //把比基准大的数移到高端 strs[high] = strs[low]; } // low==height时,返回基准值的正确位置 strs[low] = tmp; return low; }
4. 后记
- 路漫漫其修远兮,吾将上下而求索。