Largest Number
Total Accepted: 2369 Total Submissions: 15947 My Submissions Question Solution
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
【解题思路】
可以参考 【九度】题目1392:排序生成最小的数
排序,求解最大数,对整个列表排序,排序规则为,相邻两数组成字符串,大的靠前。
Total Accepted: 2369 Total Submissions: 15947 My Submissions Question Solution
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
【解题思路】
可以参考 【九度】题目1392:排序生成最小的数
排序,求解最大数,对整个列表排序,排序规则为,相邻两数组成字符串,大的靠前。
Java AC 273ms
public class Solution {
public String largestNumber(int[] num) {
int len = num.length;
String array[] = new String[len];
for (int i = 0; i < len; i++) {
array[i] = String.valueOf(num[i]);
}
Arrays.sort(array, new MySort());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++) {
sb.append(array[i]);
}
String result = sb.toString();
if ("".equals(result.replace("0",""))) {
return "0";
}
return sb.toString();
}
public class MySort implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return (o2 + o1).compareTo(o1 + o2);
}
}
}
Python AC 132ms
class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
num = sorted(num, cmp=lambda x, y: cmp(str(y) + str(x), str(x) + str(y)))
print num
sb = ''
for x in num:
sb += str(x)
if sb.replace('0', '') == '':
return '0'
return sb