数组排列成最小的数
作者:
怎样会更好 | 来源:发表于
2018-11-04 21:48 被阅读0次
题目
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.ArrayList;
public class Solution {
public String PrintMinNumber(int[] numbers) {
if (numbers.length == 0) {
return "";
}
StringBuffer sb = new StringBuffer(10);
ArrayList<String> a = new ArrayList<>();
for (int i = 0; i < numbers.length; i++) {
a.add(String.valueOf(numbers[i]));
}
while (!a.isEmpty()) {
sb.append(maxInt(a));
}
return sb.toString();
}
public String maxInt(ArrayList<String> list) {
int min = Integer.parseInt(list.get(0));
int _index = 0;
for (int i = 0; i < list.size(); i++) {
String index = list.get(i);
if (String.valueOf(min).length() > index.length()) {
for (int j = 0; j < String.valueOf(min).length()-index.length(); j++) {
index+="9";
}
if(min > Integer.parseInt(index)){
min = Integer.parseInt(list.get(i));
_index = i;
continue;
}
}
if (String.valueOf(min).length() < index.length()) {
String maxS = String.valueOf(min);
for (int j = 0; j < index.length()-String.valueOf(min).length(); j++) {
maxS+="9";
}
if(Integer.parseInt(maxS) > Integer.parseInt(index)){
min = Integer.parseInt(list.get(i));
_index = i;
continue;
}
}
if (String.valueOf(min).length() == index.length()) {
if (min > Integer.parseInt(index)) {
min = Integer.parseInt(index);
_index = i;
}
continue;
}
}
list.remove(_index);
return String.valueOf(min);
}
}
本文标题:数组排列成最小的数
本文链接:https://www.haomeiwen.com/subject/stwdxqtx.html
网友评论