LeetCode – Largest Number (Java)

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. (Note: The result may be very large, so you need to return a string instead of an integer.)

Analysis

This problem can be solve by simply sorting strings, not sorting integer. Define a comparator to compare strings by concat() right-to-left or left-to-right.

Java Solution

public String largestNumber(int[] nums) {
    String[] arr = new String[nums.length];
    for(int i=0; i<nums.length; i++){
        arr[i]=String.valueOf(nums[i]);
    }
 
    Arrays.sort(arr, new Comparator<String>(){
        public int compare(String a, String b){
            return (b+a).compareTo(a+b);
        }
    });
 
    StringBuilder sb = new StringBuilder();
    for(String s: arr){
        sb.append(s);
    }
 
    while(sb.charAt(0)=='0'&&sb.length()>1)
        sb.deleteCharAt(0);
 
    return sb.toString();
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Jangku

    your comparison doesn’t work : i.e., “45” , “4”
    should be “454” instead of “445”

  • Ankit Shah

    Using collections.sort of string

    public class LargestNumber {
    private static String largestNumber(int[] a) {
    final String sortString = "0123456789";
    StringBuffer result = new StringBuffer();
    List list = new ArrayList();
    for (int i = 0; i < a.length; i++) {
    String element = String.valueOf(a[i]);
    for (int j = 1; j <= element.length(); j++) {
    list.add(element.substring(j - 1, j));
    }
    }

    Collections.sort(list, new Comparator() {
    public int compare(String s1, String s2) {
    return sortString.indexOf(s2) - sortString.indexOf(s1);
    }
    });

    System.out.println(list);

    for (String element : list) {
    result = result.append(element);
    }
    return result.toString();
    }

    public static void main(String[] args) {
    int[] a = { 3, 30, 34, 5, 9 };
    System.out.println(largestNumber(a));
    }

    }