方法一:Arrays.sort()
package com. hc. ArrayAndString ;
import java. util. Arrays ;
import java. util. Comparator ;
public class Offer45 {
public String minNumber ( int [ ] nums) {
String [ ] strs = new String [ nums. length] ;
for ( int i = 0 ; i < nums. length; i++ )
strs[ i] = String . valueOf ( nums[ i] ) ;
Arrays . sort ( strs, new Comparator < String > ( ) {
@Override
public int compare ( String o1, String o2) {
return ( o1 + o2) . compareTo ( ( o2 + o1) ) ;
}
} ) ;
StringBuilder str = new StringBuilder ( ) ;
for ( String s : strs)
str. append ( s) ;
return str. toString ( ) ;
}
}
class TestOffer45 {
public static void main ( String [ ] args) {
Offer45 offer45 = new Offer45 ( ) ;
int [ ] nums = { 3 , 30 , 34 , 5 , 9 } ;
System . out. println ( offer45. minNumber ( nums) ) ;
}
}
方法二:快速排序
package com. hc. ArrayAndString ;
public class Offer45 {
public String minNumber ( int [ ] nums) {
String [ ] strs = new String [ nums. length] ;
for ( int i = 0 ; i < nums. length; i++ )
strs[ i] = String . valueOf ( nums[ i] ) ;
quickSort ( strs, 0 , strs. length - 1 ) ;
StringBuilder str = new StringBuilder ( ) ;
for ( String s : strs)
str. append ( s) ;
return str. toString ( ) ;
}
void quickSort ( String [ ] strs, int left, int right) {
if ( left < right) {
int i = left, j = right;
String temp = strs[ left] ;
while ( i < j) {
while ( ( strs[ j] + strs[ left] ) . compareTo ( ( strs[ left] + strs[ j] ) ) >= 0 && i < j)
j-- ;
while ( ( strs[ i] + strs[ left] ) . compareTo ( ( strs[ left] + strs[ i] ) ) <= 0 && i < j)
i++ ;
temp = strs[ i] ;
strs[ i] = strs[ j] ;
strs[ j] = temp;
}
strs[ i] = strs[ left] ;
strs[ left] = temp;
quickSort ( strs, left, i - 1 ) ;
quickSort ( strs, i + 1 , right) ;
}
}
}
class TestOffer45 {
public static void main ( String [ ] args) {
Offer45 offer45 = new Offer45 ( ) ;
int [ ] nums = { 3 , 30 , 34 , 5 , 9 } ;
System . out. println ( offer45. minNumber ( nums) ) ;
}
}