68.把数组排成最小的数

来源:互联网 发布:什么软件女人开放 编辑:程序博客网 时间:2024/05/16 04:48
题目:输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。
例如输入数组{32, 321},则输出这两个能排成的最小数字32132。
请给出解决问题的算法,并证明该算法。

分析:这是09 年6 月份百度的一道面试题,从这道题我们可以看出百度对应聘者在算法方面有很高的要求。



HANDWRITING:

关键问题在于怎么排,从头依次比较数字,小者在前,若有a比b长,则比较长的那一位是否比首位大

bool compare(int a, int b) {int al = 1, bl = 1, at = a, bt = b;for (; at > 10; al *= 10, at /= 10);for (; bt > 10; bl *= 10, bt /= 10);while (al != 0 && bl != 0) {if (a / al == b / bl) al /= 10, bl /= 10;else return a/al < b/bl;}if (al == 0) return at < (b%bl);else return (a%al) < bt;}
1、写完脑子全乱了,绕来绕去,还是想多了



好的思路:将两数m, n拼一下,比较mn和nm的大小即可得到顺序,另外mn拼接完的数字int可能存不下,需要字符串来存

貌似下面这份代码是JAVA写的,不过不影响观看

ANSWER:

FROM:http://blog.csdn.net/v_july_v/article/details/6870251
Actually this problem has little to do with algorithm...
The concern is, you must figure out how to arrange to achieve a smaller figure.
The answer is, if ab < ba, then a < b, and this is a total order.

String smallestDigit(int a[]) {  Integer aux[] = new Integer[a.length];  for (int i=0; i<a.length; a++) aux[i] = a[i];  Arrays.sort(aux, new Comparator<Integer>(){    int compareTo(Integer i1, Integer i2) {      return (“”+i1+i2).compare(“”+i2+i1);    }  });  StringBuffer sb = new StringBuffer();  for (int i=0; i<aux.length, i++) {    sb.append(aux[i]);  }  return sb.toString();}

原创粉丝点击