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.

Solution:
1: sort the number, compare the digits of number from left to right, the largest should be first.
like: compare {89,9}, the first digit 9 is largest, sort as {9,89} so the combined 989 is largest.
2. if the digits are same like {2332,23}, we have to compare left digits with shortest number again to determine which is first, 32 > 23, so sorted as {2332,23}
3. We can find trick, for each two number, we can find the law: combine numbers in both way as strings, {89,9} = {899,989}, then compare the strings so we can sort the numbers

For list, override Collections.sort()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public String largestNumber(final List<Integer> a) {
        if(a == null)
            return "0";
        Collections.sort(a, new Comparator<Integer>(){
            @Override
            public int compare(Integer n1, Integer n2){
                String s1 = String.valueOf(n1);
                String s2 = String.valueOf(n2);
                return (s2+s1).compareTo(s1+s2);
            }
        });
        if(a.get(0) == 0)
            return "0";
       StringBuffer sb = new StringBuffer();
       for(Integer i : a){
           sb.append(i);
       }
       return sb.toString();
    }

For Arrays, write Comparator function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 public String largestNumber(int[] nums) {
        Integer[] ints = new Integer[nums.length];
        int index = 0;
        for(int i : nums){
            ints[index++] = i;
        }
        Arrays.sort(ints,new Comparator<Integer>(){
            public int compare(Integer n1, Integer n2){
                String s1=String.valueOf(n1);
                String s2=String.valueOf(n2);
                return (s2+s1).compareTo(s1+s2);
            }
        });
       
        if(ints[0] == 0)
            return "0";
        StringBuilder sb = new StringBuilder();
        for(Integer i : ints){
            sb.append(i);
        }
       
        return sb.toString();
    }