一、问题描述:
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.
二、解决思路:
思路以及证明见剑指Offer中的题目“最小的数字”。
重写sort方法,将Int类型转化为string类型(拼接之后的数字范围可能会超出int的范围)对于m和n, 如果 mn > nm 那么 m排n前边,否则m在n后边。
三、代码:
package T01;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author 作者 : xcy
* @version 创建时间:2017年1月1日 下午8:51:00
* 类说明
*/
public class t179 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = { 0, 0, 1 };
System.out.println(largestNumber(nums));
}
public static String largestNumber(int[] nums) {
List<String> tmp = new ArrayList<String>();
for (int i : nums) {
tmp.add(i + "");
}
Collections.sort(tmp, new Comparator<String>() {
@Override
public int compare(String arg0, String arg1) {
return compareString(arg0, arg1);
}
});
StringBuffer re = new StringBuffer();
int index = 0;
for (int i = 0; i < tmp.size(); i++) {
if (tmp.get(i).equals("0")) {
index++;
} else {
break;
}
}
if (index == tmp.size()) {
index--;
}
for (int i = index; i < tmp.size(); i++) {
re.append(tmp.get(i));
}
return re.toString();
}
public static int compareString(String s1, String s2) {
int re = 0;
String tmp = s1;
s1 = s1 + s2;
s2 = s2 + tmp;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) < s2.charAt(i)) {
return 1;
}
if (s1.charAt(i) > s2.charAt(i)) {
return -1;
}
}
return re;
}
}