F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[Leetcode] Largest Number

再次熟悉java当中的comparator的写法

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.

 

这里的一个Corner case 是我们需要考虑0的出现:

如果全是零,那么返回“0”

如果有零的存在,需要在最后的最大数字的后面append上相应的零。

 

 1 import java.util.*;
 2 
 3 public class Solution {
 4     private class mycompare implements Comparator<String>{
 5         public int compare(String i1, String i2){
 6             String i12 = i1+""+i2;
 7             String i21 = i2+""+i1;
 8             return -i12.compareTo(i21);
 9         }
10     }
11     public String largestNumber(int[] nums) {
12         //Arrays.sort(nums,new mycompare());
13         Vector<String> strs = new Vector<String>();
14         int zerocount=0;
15         for(int i: nums){
16             if(i==0) zerocount++;
17             else strs.add(i+"");
18         }
19         Collections.sort(strs,new mycompare());
20         String res="";
21         for(int i=0;i<strs.size();i++){
22             res = res + strs.get(i);
23         }
24         if(strs.size()==0) return "0";
25         else{
26             for(int i=0;i<zerocount;i++){
27                 res=res+"0";
28             }
29         }
30         return res;
31     }
32 }

 

posted on 2015-08-17 10:24  F_G  阅读(147)  评论(0编辑  收藏  举报