题目
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
思路
拼接字符串,本质上是一个排序问题,排序规则为:
(1)若拼接后的字符串, x + y > y + x
,则 排序完成后,x
应该在 y
右边
(2)若拼接后的字符串, x + y < y + x
,则 排序完成后,x
应该在 y
左边
比如:x = 5 , y = 7,x + y = "57", y + x = "75"
,因为 x + y < y + x
,所以排序后x
在前面,y
在后面
方法一:快速排序
需要修改快速排序函数中的排序判断规则
java代码如下:
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]);//将nums[i]转成String类型
}
quickSort(strs, 0, strs.length - 1);//对strs进行排序
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 pivot = partition(strs, low, high);
quickSort(strs, low, pivot - 1);
quickSort(strs, pivot + 1, high);
}
}
public int partition(String[] strs, int low, int high){
//数组第一个元素为基准元素(枢轴)
String pivot = strs[low];//保存副本,方便后序比较操作
while(low < high){
//从后往前找第一个比基准小的元素,因为要按照升序排列,从而保证拼接的结果最小
while(low < high && (strs[high] + pivot).compareTo(pivot + strs[high]) >= 0){//循环条件中,只要(strs[high] + pivot).compareTo(pivot + strs[high]) >= 0 说明 strs[high] + pivot > pivot + strs[high],即意味着排序后strs[high]是在pivot的后面的
high--;//循环条件满足则不断前移,直到找到不满足的位置,即比基准小的数,也就是排序后strs[high]是要在pivot前面的位置
}
//把比基准小的数移到低端
strs[low] = strs[high];
//再从前往后找第一个比基准大的数
while(low < high && (strs[low] + pivot).compareTo(pivot + strs[low]) <= 0){//循环条件中,只要(strs[low] + pivot).compareTo(pivot + strs[low]) <= 0 说明 strs[low] + pivot < pivot + strs[low],即意味着排序后strs[low]是在pivot的前面的
low++;//循环条件满足则不断后移,直到找到不满足的位置,即比基准大的数,也就是排序后strs[low]是要在pivot后面的位置
}
//把比基准大的数据移到高端
strs[high] = strs[low];
}
strs[low] = pivot;// 将基准值插入到首部和尾部中间位置,注意此时的low不是起始位置,而是已经走到了中间位置
return low;// 返回基准值的位置
}
}
方法二:内置函数
java代码如下:
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));//重新定义排序顺序,按照x+y < y+x形成升序,从而保证拼接的最小值
StringBuilder res = new StringBuilder();
for(String s : strs)
res.append(s);
return res.toString();
}
}