首页 > 代码库 > 179. Largest Number

179. Largest Number

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.

 1 public class Solution {
 2     public String largestNumber(int[] nums) {
 3         if(nums==null||nums.length==0) return "";//corner case:if the input array is null or the length of array is zero
 4         // covert int array into string array so that we can sort it later
 5         String[] s_nums = new String[nums.length];
 6         for(int i=0;i<s_nums.length;i++){
 7             s_nums[i] = String.valueOf(nums[i]);
 8         }
 9         // Comparator to decide which string come first in concatenation
10         Comparator<String> com = new Comparator<String>(){
11             public int compare(String str1,String str2){
12                 String s1 = str1+str2;
13                 String s2 = str2+str1;
14                 return s2.compareTo(s1);
15             }
16         };
17         // sort the string array
18         Arrays.sort(s_nums,com);
19         // an extreme edge case, to consider all of the int array elements are zero
20         if(s_nums[0].charAt(0)==‘0‘) return "0";
21         StringBuilder sb = new StringBuilder();
22         for(int i=0;i<s_nums.length;i++){
23             sb.append(s_nums[i]);
24         }
25         return sb.toString();
26     }
27 }
28 //As for the run time complexity,suppose the average string length is k,the comparator takes O(k)time,the sort takes nlongn time,so the total time costs knlongn time.As for the space complexity,O(n);

 

179. Largest Number