179. Largest Number

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.

Notice for Java

  • int[] and Comparator is illegal.
  • String compareTo and Comparator's compare.
public class Solution {
    public String largestNumber(int[] nums) {
        Integer[] ints = new Integer[nums.length];
        int i=0;
        for(int v : nums){
            ints[i++] =v;
        }
        Comparator<Integer> comp = new Comparator<Integer>(){
            @Override
            public int compare(Integer s1, Integer s2){
                String c1 = Integer.toString(s1) + Integer.toString(s2);
                String c2 = Integer.toString(s2) + Integer.toString(s1);

                return 0 - c1.compareTo(c2);
            }
        };

        Arrays.sort(ints, comp);

        if(ints[0] == 0) return "0";

        StringBuilder sb = new StringBuilder();
        for(int v : ints){
            sb.append(v);
        }

        return sb.toString();
    }
}

results matching ""

    No results matching ""