LeetCode: LargestNumber

This is the first problem I tried on the leetCode:

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.

The idea is straightfoward. Firstly sort the input array and then change it to String and concatenate them together. The trick thing is that how to define "larger". For instance, 1211 is larger than 121, but 1211211 is larger than 1211121, so we need to override the compareTo method to put the larger digit in the front.  The simplest way is comparing "a+b" and "b+a".

There is a 5 lines code on the discuss:

internal static string LargestNumber(List<int> vals)
        {
            if(vals==null || vals.Count==0)
                return "";
            vals.Sort((a,b)=>String.Compare(b+""+a,a+""+b));
            return vals[0]==0?"0":String.Join("",vals);
        }

 

Note that C# support the anonymous method to re-define the compareTo method. We can also write the java version by using the lambda expression:
public String largestNumber(int[] num) {
      String[] sNum = new String[num.length];
      for(int i = 0;i<num.length; i++){
             sNum[i] = Integer.toString(num[i]);
        }
        Arrays.sort(sNum,(n1, n2) -> (n2 + n1).compareTo(n1 + n2));
        String s = String.join("",sNum);
        return (s.charAt(0) == '0')? "0":s ;
    }

 

notice that:

1. we should use Arrays.sort(), not Collections.sort(), because according to the oracle document:

sort( Collections)

public static  void sort(List list,
                            Comparator<? super T> c)

sort(Arrays)

public static  void sort(T[] a,
                            Comparator<? super T> c)

so the Arrays.sort sorts an array, while Collections.sort() sorts a list.

2. we are supposed to sort them in increasing order so it should be

(n2 + n1).compareTo(n1 + n2)

not

(n1 + n2).compareTo(n2 + n1)
posted @ 2015-06-19 10:20  SeanYuan  阅读(100)  评论(0编辑  收藏  举报