Java Solution 120ms, beats 95%


  • 0
    E
    public class Solution {
        public String largestNumber(int[] nums) {
            List<String> l = new ArrayList<String>();
            for(int n : nums) l.add("" + n);
            Collections.sort(l, new Comparator(){
                public int compare(Object oa, Object ob) { 
                    String sa = (String)oa, sb = (String)ob;
                    char[] a = sa.toCharArray();
                    char[] b = sb.toCharArray();
                    int la = a.length, lb = b.length;
                    int l = la<lb ? la : lb, i=0;
                    while(i<l && a[i]==b[i]) i++;
                    if(i==la && i==lb) return 0;
                    if(i==la) return compare(sa, sb.substring(i));
                    if(i==lb) return compare(sa.substring(i), sb);
                    return a[i]>b[i] ? -1 : 1;
                } 
            }); 
            if(l.get(0).equals("0")) return "0";
            String res = "";
            for(String s : l) res += s;
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.