码迷,mamicode.com
首页 > 其他好文 > 详细

179. Largest Number

时间:2015-04-09 11:48:24      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

排序,O(nlgn)

public class Solution {
  public String largestNumber(int[] num) {
    List<String> numStr = new ArrayList<>(num.length);
    for(int n : num) {
      numStr.add(String.valueOf(n));
    }
    Comparator<String> comp = new Comparator<String>() {
      @Override
      public int compare(String s1, String s2) {
        String num1 = s1 + s2;
        String num2 = s2 + s1;
        return num1.compareTo(num2);
      }
    };
    Collections.sort(numStr, comp);

    if (Integer.parseInt(numStr.get(num.length-1)) == 0) {
      return "0";
    }

    StringBuilder sb = new StringBuilder();
    for(String s : numStr) {
      sb.insert(0, s);
    }

    return sb.toString();
  }
}

179. Largest Number

标签:

原文地址:http://www.cnblogs.com/shini/p/4409213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!