Leetcode 179. Largest Number (Medium) (java)
Tag: Sort
Difficulty: Medium
/*
179. Largest Number (Medium)
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.
*/
public class Solution {
public String largestNumber(int[] num) {
if(num == null || num.length == 0) return "";
String[] s_num = new String[num.length];
for(int i = 0; i < num.length; i++)
s_num[i] = String.valueOf(num[i]);
Comparator<String> comp = new Comparator<String>(){
public int compare(String str1, String str2){
String s1 = str1 + str2;
String s2 = str2 + str1;
return s2.compareTo(s1);
}
};
Arrays.sort(s_num, comp);
if(s_num[0].charAt(0) == '0') return "0";
StringBuilder sb = new StringBuilder();
for(String s: s_num)
sb.append(s);
return sb.toString();
}
}