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)

转载于:https://www.cnblogs.com/xyuan14/p/4587840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值