码迷,mamicode.com
首页 > 其他好文 > 详细

179. Largest Number

时间:2017-05-20 10:13:39      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:null   ace   class   ext   ges   long   cas   ons   amp   

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

标签:null   ace   class   ext   ges   long   cas   ons   amp   

原文地址:http://www.cnblogs.com/codeskiller/p/6880818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!