179. Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2] Output: "210"
Example 2:
Input: [3,30,34,5,9] Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
思路:
贪心的思想,比较相邻两个字符串拼接结果,比较大小。
代码:
java:
代码语言:javascript复制class Solution {
public String largestNumber(int[] nums) {
if (nums == null || nums.length == 0) return "";
int len = nums.length;
String [] strs = new String[len];
for (int i = 0; i < len; i ) {
strs[i] = String.valueOf(nums[i]);
}
Comparator<String> comp = new Comparator<String>(){
@Override
public int compare(String str1, String str2) {
String s1 = str1 str2;
String s2 = str2 str1;
return s2.compareTo(s1);
}
};
Arrays.sort(strs, comp);
if(strs[0].charAt(0) == '0') return "0";
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s);
}
return sb.toString();
}
}