2015年10月24日星期六

Leetcode 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.
Solution 1: use the comparator interface
 public class Solution {  
   class MSBcompare implements Comparator<String> {  
     @Override  
     public int compare(String a, String b){  
       return (a+b).compareTo(b+a);  
     }  
   }  
   public String largestNumber(int[] nums) {  
     int n=nums.length;  
     String[] s=new String[n];  
     for (int i=0; i<n; i++) s[i]=String.valueOf(nums[i]);  
     Arrays.sort(s,new MSBcompare());  
     StringBuilder sb=new StringBuilder();  
     for (int i=n-1; i>=0; i--) sb.append(s[i]);  
     int i=0;  
     while (sb.charAt(i)=='0' && i<n-1) i++;  
     return sb.substring(i);  
   }  
 }  

没有评论:

发表评论