先把数字转成string 写个自定义排序就行
我写了两种比较两个string的大小
直接相加再比较数字 较慢
@Override
public int compare(String a, String b) {
int o1 = Integer.parseInt(a+b);
int o2 = Integer.parseInt(b+a);
return o1 - o2;
}
手动一位一位比较 较快
@Override
public int compare(String a, String b) {
int ax = 0, bx = 0, av = 0, bv = 0;
while (ax*bx < 2 && a.charAt(av) == b.charAt(bv)){
if (++av == a.length()) {av = 0;++ax;}
if (++bv == b.length()) {bv = 0;++bx;}
}
return a.charAt(av) - b.charAt(bv);
}
stream写法 直接return 但是stream对string处理速度慢一些
class Solution {
public String printMinNumber(int[] nums) {
return nums.length == 0 ? "" :
Arrays.stream(nums)
.mapToObj(String::valueOf)
.sorted((a,b) -> {
int ax = 0, bx = 0, av = 0, bv = 0;
while (ax*bx < 2 && a.charAt(av) == b.charAt(bv)){
if (++av == a.length()) {av = 0;++ax;}
if (++bv == b.length()) {bv = 0;++bx;}
}
return a.charAt(av) - b.charAt(bv);
})
.reduce((a,b) -> a+b)
.get();
}
}
正常写法 速度几乎提升一倍
class Solution {
public String printMinNumber(int[] nums) {
String[] strings = new String[nums.length];
for (int i = 0; i < nums.length; ++i) {
strings[i] = String.valueOf(nums[i]);
}
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String a, String b) {
int av = 0, bv = 0, ax = 0, bx = 0;
while (ax*bx < 2 && a.charAt(av) == b.charAt(bv)){
if (++av == a.length()) {av = 0;++ax;}
if (++bv == b.length()) {bv = 0;++bx;}
}
return a.charAt(av) - b.charAt(bv);
}
});
StringBuilder res = new StringBuilder();
for (String str : strings) {
res.append(str);
}
return res.toString();
}
}