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 }

 

posted on 2015-01-15 17:18  Step-BY-Step  阅读(122)  评论(0编辑  收藏  举报

导航