The Code Sniper: 179. Largest Number Leetcode Java
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 String largestNumber(int[] num) {
if(num==null || num.length==0) return "";
String[] temp=new String[num.length];
for(int i=0;i<num.length;i++){
temp[i]=String.valueOf(num[i]);
}
Comparator<String> myComparator=new Comparator<String>(){
@Override
public int compare(String a, String b){
String sa=a+b;
String sb=b+a;
return sb.compareTo(sa);
}
};
Arrays.sort(temp,myComparator);
if(temp[0].equals("0")) return "0";
StringBuilder sb=new StringBuilder();
for(int i=0;i<temp.length;i++){
sb.append(temp[i]);
}
return sb.toString();
}
http://lixinzhang.github.io/itint5-mian-shi-ti-zong-jie.htmlbool cmp(string s1, string s2){ int size = min(s1.size(), s2.size()); for(int i=0; i<size; i++){ if(s1[i] == s2[i]) continue; return s1[i] > s2[i]; } if (s1.size() > s2.size()) { return cmp(s1.substr(size, s1.size() - size), s2); }else if(s1.size() < s2.size()){ return cmp(s1, s2.substr(size, s2.size() - size)); } /* 比较函数必须保证是一个全序关系,因此必须有反对称性, 即若a<b则b<a不成立。你定义的比较函数,对于重合区间a,b, a<b和b<a同时成立,因此sort会core。 */ return false; } bool cmp2(string s1, string s2){ //之前的cmp写复杂了,主要保证s1+s2与s2+s1之间的关系即可 return s1+s2 > s2+s1; } string biggestNum(vector<string> &nums) { sort(nums.begin(), nums.end(), cmp2); string res = ""; for(unsigned i=0; i<nums.size(); i++){ res += nums[i]; } return res; }Read full article from The Code Sniper: 179. Largest Number Leetcode Java