Java Solution without s1+s2 vs s2+s1 approach


  • 1
    C

    public String largestNumber(int[] nums) {

        char[][] vals = new char[nums.length][];
        
        for( int i = 0; i < nums.length; i++ ){
            vals[i] = (""+nums[i]).toCharArray();
        }
        
        Arrays.sort(vals, new Comparator<char[]>(){
            
            public int compare(char[] val1, char[] val2){
                for(int i = 0; i < val1.length || i < val2.length || i%val2.length != i%val1.length; i++){
                    char c1 = val1[i%val1.length];
                    char c2 = val2[i%val2.length];
                    if(c1 != c2){
                        return c2-c1;
                    }
                }
                
                return 0;
            }
          
        });
        
        StringBuilder builder = new StringBuilder();
        
        for(int i = 0; i < nums.length;  i++){
            builder.append(vals[i]);
        }
        
        String ret = builder.toString();
        
        return ret.startsWith("0") ? "0" : ret;
    
    }

Log in to reply
 

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