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.
Subscribe to see which companies asked this question
public class Solution2 {
private static CompareStary compStary = new CompareStary();
public static void main(String[] args) {
test(new int[]{128,12});
}
public static String test(int nums[])
{
String ret ="";
int length = nums.length;
if(length > 0)
{
List<List<String>> lst= new ArrayList<List<String>>();
for(int i = 0; i <= 9;i++)
{
lst.add(new ArrayList<String>());
}
for(int i = 0; i < nums.length;i++)
{
String str = nums[i]+"";
int temp = (int)(str.charAt(0) - '0');
List<String> lstTemp = lst.get(temp);
lstTemp.add(nums[i]+"");
}
for(int i = 0;i <= 9;i++)
{
List<String> temp= (List<String>)lst.get(i);
if(temp.size() != 0 && temp.size() != 1)
{
Collections.sort(temp, compStary);
}
}
StringBuffer sb = new StringBuffer();
ret = "";
for(int i = 9;i >= 0;i--)
{
List<String> fin = (List<String>)lst.get(i);
if(fin.size() != 0)
{
for(int j = fin.size() - 1;j >= 0; j--)
{
sb = sb.append(fin.get(j));
}
}
}
ret = sb.toString();
System.out.println(ret);
}
return ret;
}
static class CompareStary implements Comparator<String>
{
@Override
public int compare(String src, String another) {
int ret = 0;
int length1 = src.length();
int length2 = another.length();
char comChar = src.charAt(0);
StringBuffer sb = new StringBuffer();
if(length1 - length2 >=0)
{
sb.append(another);
int temp = length1 - length2;
for(int i = 0;i < temp;i++)
{
sb.append(comChar);
}
another = sb.toString();
}
else
{
sb.append(src);
int temp = length2 - length1;
for(int i = 0;i < temp;i++)
{
sb.append(comChar);
}
src = sb.toString();
}
ret = deal(src,another);
return ret;
}
private int deal(String src, String another){
char v1[] = src.toCharArray();
char v2[] = another.toCharArray();
int length = src.length();
for(int k = 0; k < length;k++)
{
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2)
{
if(c1 - c2 > 0)
{
return 1;
}
else if(c1 - c2 < 0)
{
return -1;
}
}
}
return 0;
}
}
}