Java Solution--An easy way to implement comparator


  • 3
    G

    Compare the concatenation result directly, so that the larger number is easily obtained.

       public String largestNumber(int[] nums) {
                if(nums.length==0)
                    return new String();
                List<String> t = new ArrayList<String>();
                int count = 0;
                for(int i=0; i<nums.length;i++){
                    if(nums[i]==0)
                        count++;
                    t.add(Integer.toString(nums[i]));
                }
                if(count==nums.length)
                    return Integer.toString(0);
                
                Collections.sort(t, new Comparator<String>(){
                    @Override
                    public int compare(String s1, String s2){
                        String front = s1+s2;
                        String end = s2+s1;
                        return front.compareTo(end)*(-1);
                        
                    }
                });
                
                StringBuilder sb = new StringBuilder();
                for(String s : t)
                    sb.append(s);
                return sb.toString();
                
            }

  • 2
    M
    public int compare(String s1, String s2){
         String front = s1+s2;
         String end = s2+s1;
         return front.compareTo(end)*(-1);
    }
    

    Why not

    public int compare(String s1, String s2){
         return (s2+s1).compareTo(s1+s2);
    }
    

    Or

    Collections.sort(t, (s1, s2) -> ((s2+s1).compareTo(s1+s2)));

  • 0
    K

    can u please explain why " return front.compareTo(end)*(-1); " and not " return front.compareTo(end); ". ?


Log in to reply
 

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