题解 | #把数组排成最小的数#
把数组排成最小的数
http://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993
class Solution {
public String PrintMinNumber(int[] numbers) {
String str = "";
//冒泡排序
for (int i = 0; i < numbers.length; i++) {
//注意比较规则,先拼接起来,再比较
for (int j = i + 1; j < numbers.length; j++) {
int a = Integer.valueOf(numbers[i] + "" + numbers[j]);
int b = Integer.valueOf(numbers[j] + "" + numbers[i]);
if (a > b) {
int t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}
}
}
//拼接排好序的数组
for (int s:numbers) {
str += s;
}
return str;
}
}
和字符串拼接之后比较的思想类似,
这里也是比较两个数值大小时,需要比较拼接之后的数字
或者用这种
StringBuffer str = new StringBuffer();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
System.out.println(list);
return str.toString();