您的位置:首页 > 其它

编写一个能将给定非负整数列表中的数字排列成最大数字的函数。例如,给定[50,2,1,9],最大数字为95021。

2017-04-01 15:48 393 查看
编写一个能将给定非负整数列表中的数字排列成最大数字的函数。例如,给定[50,2,1,9],最大数字为95021。

/**
* This algorithm offers guaranteed n*log(n) performance.
*
* @param array
* @return
*/
public static String getLargestNumByArranged(Integer[] array) {
Arrays.sort(array, new Comparator<Object>() {
/***
* 默认是从小到大排序 if the result > 0 then swap
*/
public int compare(Object o1, Object o2) {
String left = o1.toString();
String right = o2.toString();
// 按字典顺序比较 if the result > 0 then * -1
return (left + right).compareTo(right + left) * -1;
// return (right + left).compareTo(left + right);
}

});

StringBuffer sb = new StringBuffer();
for (Integer integer : array) {
sb.append(integer.toString());
}

return sb.toString();
}

public static void main(String[] args) {
Integer[] VALUES = { 50, 2, 100, 99, 5, 7, 51, 50, 11 };
System.out.println(getLargestNumByArranged(VALUES));
}


本文参考:

http://www.genshuixue.com/i-cxy/p/8018152
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐