面试题45. 把数组排成最小的数

题目

输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
在这里插入图片描述

思路

拼接字符串,本质上是一个排序问题,排序规则为:

(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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HDU-五七小卡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值