题目:
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.
解题思路:
先把int数组转为String,然后做一个比较器,这里有一个小技巧可以用 (o2 + o1).compareTo(o1 + o2)作为比较器,可以将"大数字"放到前面,然后按照比较器的顺序输出即可,JAVA实现如下:
代码:
import java.util.Arrays;
import java.util.Comparator;
public class LargestNumber
{
public static void main(String[] args)
{
/**
* Given a list of non negative integers, arrange them such that they form the largest number.
*/
/**
* Example 1:
* Input: [10,2]
* Output: "210"
*/
int[] nums1 = { 10, 2 };
System.out.println(largestNumber(nums1));
/**
* Example 2:
* Input: [3,30,34,5,9]
* Output: "9534330"
*/
int[] nums2 = { 3, 30, 34, 5, 9 };
System.out.println(largestNumber(nums2));
}
public static String largestNumber(int[] nums)
{
if (nums == null || nums.length == 0)
{
return "";
}
Comparator<String> comparator = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return (o2 + o1).compareTo(o1 + o2);
}
};
String[] s = new String[nums.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++)
{
s[i] = String.valueOf(nums[i]);
}
Arrays.sort(s, comparator);
if (s[0].charAt(0) == '0')
{
return "0";
}
for (int i = 0; i < s.length; i++)
{
sb.append(s[i]);
}
return sb.toString();
}
}