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

Largest Number

时间:2015-01-15 19:50:51      阅读:94      评论: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.

注意:

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 }

 

Largest Number

标签:

原文地址:http://www.cnblogs.com/reynold-lei/p/4226810.html

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