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.
代码
Approach #1 Sorting via Custom Comparator
classSolution {publicStringlargestNumber(int[] nums) {String[] asStrs =newString[nums.length];for (int i =0; i <nums.length; i++) { asStrs[i] =String.valueOf(nums[i]); }Arrays.sort(asStrs,newLargerNumberComparator());if (asStrs[0].equals("0")) {return"0"; }String largestNumberStr =newString();for (String numAsStr : asStrs) { largestNumStr += numAsStr; }return largestNumberStr; }privateclassLargerNumberComparatorimplementsComparator<String> { @Overridepublicintcompare(String a,String b) {String order1 = a + b;String order2 = b + a;returnorder2.compareTo(order1); } }}