Monday, January 12, 2015

Largest Number (LeetCode Sort)

Question: 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.

Idea: First convert the numbers to string format. Then sort the strings following the rule: if "put string s1 in front of s2" makes a bigger number than "put string s2 in front of s1", place s1 after s2 in the sorted string array. Then scan the array from the last string to construct the output result.
Since the input may be "0" "0" "0" -> "000", we need to remove the leading zeros.

Time: O(nlgn) Space: O(n^2) (assume there are n integers each with n digits)

Code:
 public class Solution {  
   public Comparator<String> comp=new Comparator<String>()  
   {  
    public int compare(String s1,String s2)  
    {  
      String firstBig=s1+s2;  
      String secondBig=s2+s1;  
      for(int i=0;i<firstBig.length();i++)  
      {  
        char c1=firstBig.charAt(i);  
        char c2=secondBig.charAt(i);  
        if(c1>c2)  
        {  
          return 1;  
        }  
        if(c1<c2)  
        {  
          return -1;  
        }  
      }  
      return 0;  
    }  
   };  
   public String largestNumber(int[] num) {  
     String[] strings=new String[num.length];  
     for(int i=0;i<num.length;i++)  
       strings[i]=Integer.toString(num[i]);  
     Arrays.sort(strings,comp);  
     StringBuilder builder=new StringBuilder();  
     for(int i=strings.length-1;i>=0;i--)  
       builder.append(strings[i]);  
     int index=0;  
     while(builder.charAt(index)=='0'&&index<builder.length()-1)  
       index++;  
     return builder.substring(index);  
   }  
 }  

No comments:

Post a Comment