题目:
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.
tips:测试用例实在变态,比较算法改了几次才通过。。。。
public class Solution {
public String largestNumber(int[] nums) {
if(nums.length==0)
return "";
String []str=new String[nums.length];
for (int i = 0; i < nums.length; i++) {
str[i]=String.valueOf(nums[i]);
}
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a=o1.concat(o2);
String b=o2.concat(o1);
boolean flag=Double.parseDouble(b)> Double.parseDouble(a);
if(flag==true)
return 1;
else
return -1;
}
});
StringBuilder sb=new StringBuilder();
for(String s:str)
sb.append(s);
int i;
for (i = 0; i <sb.toString().length() ; i++) {
if(sb.toString().charAt(i)!='0')
break;
}
if(i==sb.toString().length())
return "0";
else
return sb.toString().substring(i);
}
}