leetcode

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.

这道题的思路就是写一个Comparator, str(i1)+str(i2)> str(i1)+str(i2), 那i1就会在i2的前面。然后Leetcode还需要考虑都是0的edge case,以及int特别大的情况。

public String largestNumber(int[] num) {        
        Comparator<Long> comp = new Comparator<Long>() {

            @Override
            public int compare(Long i1, Long i2) {
                String r1 = i1+""+i2;
                String r2 = i2+""+i1;

                if (Long.parseLong(r1)>Long.parseLong(r2)) {
                    return -1;
                } else {
                    return 1;
                }
            }

        };

        Long[] array = convert(num);
        Arrays.sort(array, comp);
        //handle all "0" case
        if (array[0]==0l) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        for (Long number : array) {
            sb.append(number);
        }
        return sb.toString();
    }

    private Long[] convert(int[] num) {
        Long[] array = new Long[num.length];
       for (int i=0; i<num.length; i++) {
           array[i] = (long)num[i];
       }
       return array;
    }