1+ /*
2+ 3+ Date: Jan 13, 2015
4+ Problem: ZigZag Conversion
5+ Difficulty: Medium
6+ Source: https://oj.leetcode.com/problems/largest-number/
7+ Notes:
8+ Given a list of non negative integers, arrange them such that they form the largest number.
9+
10+ For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
11+
12+ Note: The result may be very large, so you need to return a string instead of an integer.
13+
14+ Solution: ...
15+ */
16+
17+ public class Solution {
18+ public String largestNumber_1 (int [] num ) {
19+ int size = num .length ;
20+ if (size <= 0 ) return new String ();
21+ if (size == 1 ) return String .valueOf (num [0 ]);
22+ Comparator <Integer > comp = new Comparator <Integer >(){
23+ public int compare (Integer a , Integer b ) {
24+ String aa = "" +a +b ;
25+ String bb = "" +b +a ;
26+ return bb .compareTo (aa );
27+ }
28+ };
29+ Integer [] in = new Integer [size ];
30+ for (int i = 0 ; i < size ; ++i )
31+ in [i ] = Integer .valueOf (num [i ]);
32+ Arrays .sort (in , comp );
33+ StringBuffer res = new StringBuffer ();
34+ int i = 0 ;
35+ while ((i < in .length - 1 ) && (in [i ] == 0 )) ++i ;
36+ while (i < in .length ) res .append (in [i ++]);
37+ return res .toString ();
38+ }
39+ public String largestNumber_2 (int [] num ) {
40+ int size = num .length ;
41+ if (size <= 0 ) return new String ();
42+ String [] in = new String [size ];
43+ for (int i = 0 ; i < size ; ++i )
44+ in [i ] = String .valueOf (num [i ]);
45+ return foo (in );
46+ }
47+ public String foo (String [] in ) {
48+ if (in .length == 0 ) return new String ();
49+ if (in .length == 1 ) return in [0 ];
50+ StringBuffer res = new StringBuffer ();
51+ Comparator <String > comp = new Comparator <String >(){
52+ public int compare (String a , String b ) {
53+ String aa = a +b ;
54+ String bb = b +a ;
55+ return bb .compareTo (aa );
56+ }
57+ };
58+ Arrays .sort (in , comp );
59+ int i = 0 ;
60+ while ((i < in .length - 1 ) && (in [i ].compareTo ("0" ) == 0 )) ++i ;
61+ while (i < in .length ) res .append (in [i ++]);
62+ return res .toString ();
63+ }
64+ }
0 commit comments