[leed code 179] Largest Number

1 题目

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

2 方法

刚开始就误入歧途,准备按字符来比较,结果逻辑各种复杂,网上查了查,结果发现直接比较两个连起来的字符串要简单的多。比如字符串a和字符串b,比较ab和ba的大小就搞定了。

3 代码

     public String largestNumber(int[] num){
String[] strArray = new String[num.length];
for (int i = 0; i < num.length; i++) {
strArray[i] = Integer.toString(num[i]);
}
strArray = this.anotherSort(strArray);//(strArray);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < strArray.length; i++) {
sb.append(strArray[i]);
}
String out = sb.toString();
if(out.charAt(0) == '0') return "0";
return out;
}
public static String[] anotherSort(String[] strSort) {
String temper = "";
for (int i = 0; i < strSort.length; i++) {
for (int j = i + 1; j < strSort.length; j++) {
String add1 = strSort[i] + strSort[j];
String add2 = strSort[j] + strSort[i];
int out = add1.compareTo(add2);
if (out < 0) {
temper = strSort[i];
strSort[i] = strSort[j];
strSort[j] = temper;
}
}
}
return strSort;
}
上一篇:关于sencha touch中给文本添加焦点无效的解决方案


下一篇:Js debug模式