题目:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数。打印能拼接出所有数字中最小的一个。
解答:
1 public class Solution { 2 3 public static void main(String[] args) { 4 int[] array = {321,32,3}; 5 printMin(array); 6 } 7 8 private static void printMin(int[] array) { 9 int[] clone = array.clone(); 10 printMin(clone, 0, clone.length-1); 11 for(int i: clone) { 12 System.out.print(i); 13 } 14 } 15 16 private static void printMin(int[] array, int start, int end) { 17 if(start < end) { 18 int main_number = array[end]; 19 int small_cur = start; 20 for(int j = start; j < end; j++) { 21 if(isSmall(String.valueOf(array[j]), String.valueOf(main_number))) { 22 int temp = array[j]; 23 array[j] = array[small_cur]; 24 array[small_cur] = temp; 25 small_cur++; 26 } 27 } 28 29 array[end] = array[small_cur]; 30 array[small_cur] = main_number; 31 printMin(array, 0, small_cur-1); 32 printMin(array, small_cur+1, end); 33 } 34 } 35 36 public static boolean isSmall(String m, String n) { 37 String left = m + n; 38 String right = n + m; 39 40 boolean result = false; 41 for(int i = 0; i < left.length(); i++) { 42 if(left.charAt(i) < right.charAt(i)) { 43 return true; 44 } else if(left.charAt(i) > right.charAt(i)) { 45 return false; 46 } 47 } 48 49 return result; 50 } 51 }