题目: https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/
此题求拼接起来的 “最小数字” ,本质上是一个排序问题。
- 排序判断规则:
设 nums 任意两数字的字符串格式 x 和 y
若拼接字符串 x + y > y + x ,则 x > y;
反之,若 x + y < y + x,则 x < y ;
根据以上规则,套用任何排序方法对 nums 执行排序即可。
使用快速排序完成
class Solution {
String[] strs = null;
public String minNumber(int[] nums) {
int len = nums.length;
if( len == 0) return null;
strs = new String[len];
for(int i = 0; i < len; i++){
strs[i] = String.valueOf(nums[i]);
}
//本质就是排序 只不过排序规则需要修改
//x + y < y + x -> x < y
//x + y > y + x -> x > y
sort(strs, 0, len - 1);
StringBuilder strbd = new StringBuilder();
for(int i = 0; i < len; i++){
strbd.append(strs[i]);
}
return strbd.toString();
}
public void sort(String[] strs, int low, int high){
if(low < high){
//中枢
int pivote = pivoteS(strs, low, high);
//中枢右边
sort(strs, pivote + 1, high);
//中枢左边
sort(strs, low, pivote - 1);
}
}
public int pivoteS(String[] strs, int low, int high){
//中枢
String pivote = strs[low];
while(low < high){
//右边 比中枢大
//前者大于后者,返回1,等于返回0,小于返回-1
while(high > low && ((strs[high] + pivote).compareTo(pivote + strs[high]) >= 0)){
high--;
}
//调换low 和 high位置的值
strs[low] = strs[high];
//左边 比中枢小
while(high > low && ((strs[low] + pivote).compareTo(pivote + strs[low]) <= 0)){
low++;
}
strs[high] = strs[low];
}
strs[high] = pivote;
//返回中枢现在的位置
return high;
}
}