My straightforward nlogn Java solution


  • 0
    T

    import java.math.BigInteger;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;

    /*

    public class LargestNumber
    {
    public String largestNumber(int[] num)
    {
    ArrayList<NumToCompareState> al = new ArrayList<NumToCompareState>();

    	for (Integer n : num)
    	{
    		al.add(new NumToCompareState(n));
    	}
    
    	StringBuilder sb = new StringBuilder("");
    	Collections.sort(al);
    	Iterator<NumToCompareState> it = al.iterator();
    
    	for (int i = 0; i < al.size(); ++i)
    	{
    		sb.append(it.next().originalNum + "");
    	}
    
    	BigInteger zero = new BigInteger("0");
    	BigInteger doom = new BigInteger(sb.toString());
    	return doom.equals(zero) ? "0" : sb.toString();
    }
    
    public static void main(String[] args)
    {
    	LargestNumber lg = new LargestNumber();
    
    	String result;
    
    	{
    		int[] a = {3, 30, 34, 5, 9};
    		result = lg.largestNumber(a);
    		System.out.println(result);
    	}
    	
    	{
    		int[] a = {121, 12};
    		result = lg.largestNumber(a);
    		System.out.println(result);
    	}
    	
    	{
    		int[] a = {0, 0};
    		result = lg.largestNumber(a);
    		System.out.println(result);
    	}	
    }
    

    }

    class NumToCompareState implements Comparable<NumToCompareState>
    {
    int originalNum;

    NumToCompareState (int originalNum)
    {
    	this.originalNum = originalNum;
    }
    
    @Override
    public int compareTo(NumToCompareState o)
    {
    	BigInteger ours = new BigInteger(originalNum + "" + o.originalNum);
    	BigInteger theirs = new BigInteger(o.originalNum + "" + originalNum);
    	return -ours.compareTo(theirs);
    }
    
    @Override
    public String toString()
    {
    	return "(" + originalNum + ")"; 
    }
    
    @Override
    public boolean equals(Object o)
    {
    	if (!(o instanceof NumToCompareState))
    		return false;
    
    	NumToCompareState other = (NumToCompareState)o;
    
    	return this.originalNum == other.originalNum; 
    }
    

    }

    The equals and toString was for debugging on my end


Log in to reply
 

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