1.题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
2.算法描述
最
左
边
的
位
置
,
应
该
是
两
两
排
列
中
产
生
最
小
数
字
的
那
个
数
\red{最左边的位置,应该是两两排列中产生最小数字的那个数}
最左边的位置,应该是两两排列中产生最小数字的那个数,
依
次
类
推
,
剩
下
的
最
左
边
的
位
置
,
应
该
是
剩
下
的
数
中
两
两
排
列
中
产
生
最
小
数
字
的
那
个
数
\red{依次类推,剩下的最左边的位置,应该是剩下的数中两两排列中产生最小数字的那个数}
依次类推,剩下的最左边的位置,应该是剩下的数中两两排列中产生最小数字的那个数, 有点选择排序的味道。
比如:{3,32,321},一开始的位置应该放321,为什么呢?
因为进行两两排列之后,
3
,
32
−
>
332
,
32
,
3
−
>
323
,
且
332
>
323
\red{3,32->332, 32,3->323,且332>323}
3,32−>332,32,3−>323,且332>323,所以如果是数组只有这两个数,32应该放在3的前面,有第三个那就再和第三个比较,
32
,
321
−
>
32321
,
321
,
32
−
>
32132
,
且
32321
>
32132
\red{32,321->32321,321,32->32132,且32321>32132}
32,321−>32321,321,32−>32132,且32321>32132,所以321应该放在最前面。
3.代码描述
3.1.Java代码
import java.util.ArrayList;
public class Solution {
public String PrintMinNumber(int [] numbers) {
StringBuilder sb = new StringBuilder();
String ab = null;
String ba = null;
for(int i=0; i< numbers.length; i++){
for(int j = i+1; j<numbers.length; j++){
ab = numbers[i] + "" + numbers[j];
ba = numbers[j] + "" + numbers[i];
if(ab.compareTo(ba) > 0){
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
sb.append(numbers[i]);
}
return sb.toString();
}
}
3.2.Python代码
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers:
return ""
if len(numbers)==0:
return ""
numbers = [str(e) for e in numbers]
numbers.sort(cmp=lambda x, y: int(x+y)-int(y+x))
return int(''.join(numbers))