Question2
nums is an array consisting of non-negative integers, please
concatenate them in certain permutation such that they can form a
smallest new integer number.
Input: nums = [1, 4, 13, 2, 25]
Output: 1132254
解题思路:
此题求拼接起来的最小数字,本质上是一个排序问题。设数组 nums 中任意两数字的字符串为 x 和 y ,则规定 排序判断规则为:
若拼接字符串 x+y>y+x,则 x “大于” y ;
反之,若 x+y<y,则 x “小于” y ;
x “小于” y代表:排序完成后,数组中 x 应在 y 左边;“大于” 则反之。
根据以上规则,套用任何排序方法对 nums 执行排序即可。
算法流程:
初始化: 字符串列表 s,保存各数字的字符串格式;
列表排序: 应用以上 “排序判断规则” ,对 s执行排序;
返回值: 拼接 s 中的所有字符串,并返回。
复杂度分析:
时间复杂度 O(NlogN)) : N 为最终返回值的字符数量( strs列表的长度 );使用快排或内置函数的平均时间复杂度为 O(NlogN) ,最差为 O(N^2)
空间复杂度 O(N): 字符串列表 strs占用线性大小的额外空间。
import java.lang.reflect.Array;
import java.util.Arrays;
class Solution {
public String minNumber(int[] nums) {
int n=nums.length;
String[]s=new String[n];
for(int i=0;i<n;i++){
s[i]= String.valueOf(nums[i]);
}
Arrays.sort(s,(x,y)->(x+y).compareTo(y+x));
String str="";
for(String s1:s){
str+=s1;
}
return str;
}
}