This question is not easy


  • 2
    M

    Especially in Java:

    To use customized comparator method, you need convert int[] to Integer[].
    When you compare two number, like "27" and "271", the simple way is to combine two numbers in different order like "27271" and "27127", then use a loop to check every digit.

    My solution for reference:

    public String largestNumber(int[] num) {
            Integer[] sorted = new Integer[num.length];
            for(int i=0;i<num.length;i++){
                sorted[i]= new Integer(num[i]);
            }
            Arrays.sort(sorted, new Comparator<Integer>(){
                @Override
                public int compare(Integer n1, Integer n2){
                    String l2 = Integer.toString(n2)+Integer.toString(n1);
                    String l1 = Integer.toString(n1)+Integer.toString(n2);
                    for(int i=0;i<l1.length();i++){
                        if(l1.charAt(i)>l2.charAt(i)) return 1;
                        else if(l1.charAt(i)<l2.charAt(i)) return -1;
                    }
                    return 0;
                }
            });
            StringBuilder sb = new StringBuilder();
            boolean flag = false;  // use a flag to eliminate the leading zero
            for(int i=sorted.length-1;i>=0;i--){
                if(sorted[i]!=0 && !flag) flag=true;
                if(flag)sb.append(sorted[i]);
            }
            if(!flag) sb.append('0');
            return sb.toString();
        }

  • 3
    Y

    My java short code, basically we have the same idea.

    public class Solution {
        public String largestNumber(int[] num) {
            String[] str=new String[num.length];
            for(int i=0;i<num.length;i++) str[i]=String.valueOf(num[i]);
            Arrays.sort(str,new Comparator<String>(){
                @Override
                public int compare(String s1,String s2){
                     return -Long.compare(Long.parseLong(s1+s2),Long.parseLong(s2+s1));
                }
            });
            if(str[0].equals("0")) return "0";
            StringBuilder res=new StringBuilder();
            for(int i=0;i<num.length;i++){
                res.append(str[i]);
            } 
            return res.toString();
        }
    }

  • 0
    Z

    That's great!

    Here is a slightly different way to override the compare method

    return Long.valueOf(s2+s1).compareTo(Long.valueOf(s1+s2));


Log in to reply
 

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