zoukankan      html  css  js  c++  java
  • 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.

    注意:

    1. 这里的比较方法是如果 a + b > b + a 则 a > b , 即 比较 30 和 34 , 因为 3034 < 3430, 所以34 比 30 大。

    2. priorityqueue 默认是从小到大输出的。 所以在comparator里面 大的return -1!

     1 public class Solution {
     2 
     3     public String largestNumber(int[] num) {
     4         PriorityQueue<Integer> pq = new PriorityQueue<Integer>(
     5             new Comparator<Integer>() {
     6                 public int compare(Integer a, Integer b){
     7                     StringBuilder sb = new StringBuilder();
     8                     sb.append(a);
     9                     sb.append(b);
    10                     int first = Integer.valueOf(sb.toString());
    11                     sb = new StringBuilder();
    12                     sb.append(b);
    13                     sb.append(a);
    14                     int second = Integer.valueOf(sb.toString());
    15                     if(first > second) return -1;
    16                     else if(first == second) return 0;
    17                     else return 1;
    18                 }
    19             }
    20         );
    21         StringBuilder sb = new StringBuilder();
    22         for(int i = 0; i < num.length; i ++){
    23             pq.add(num[i]);
    24         }
    25         for(int i = 0; i < num.length; i ++){
    26             sb.append(pq.poll());
    27         }
    28         return sb.charAt(0) == '0' ? new String("0") : sb.toString();
    29     }
    30 }
  • 相关阅读:
    configure错误列表供参考
    php和AJAX用户注册演示程序
    php中文汉字截取函数
    阻止a标签点击跳转刷新
    js日期插件
    apache 开启Gzip网页压缩
    查询文章的上下篇Sql语句
    thinkphp简洁、美观、靠谱的分页类
    thinkphp自定义模板标签(二)
    thinkphp自定义模板标签(一)
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4226810.html
Copyright © 2011-2022 走看看