【面试题33】把数组排成最小的数

【题目描述】

输入一个正整数数组,把数组里所有的数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

例如,输入数组{3,32,321},则打印出这三个数字能排成的最小数字321323。

【本题考点】

1. 很难想出新的比较规则来排序一个数组;

2. 很难证明根据这个规则排序之后的数组,把数字连接在即时最小的数字;

3. 考察解决大数问题,int相加可能溢出,可以采用字符串比较来解决;

【解决方案】

我的代码实现,仅供参考:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int[] arr = new int[] { 2, 1 };
14             PrintMinNumber(arr);
15         }
16 
17         public static void PrintMinNumber(int[] arr)
18         {
19             if (arr == null || arr.Length < 1)
20                 return;
21 
22             string[] strs = new string[arr.Length];
23 
24             for (int i = 0; i < arr.Length; i++)
25             {
26                 strs[i] = arr[i].ToString();
27             }
28 
29             Array.Sort(strs, new MyCompare());
30 
31             foreach (string str in strs)
32             {
33                 Console.Write(str);
34             }
35         }
36     }
37 
38     public class MyCompare : IComparer
39     {
40         public int Compare(object objA, object objB)
41         {
42             string strA = (string)objA;
43             string strB = (string)objB;
44 
45             string beginA = strB.Insert(0, strA);
46             string beginB = strA.Insert(0, strB);
47 
48             return beginA.CompareTo(beginB);
49         }
50     }
51 }
原文地址:https://www.cnblogs.com/HuoAA/p/4825311.html