把数组排成最小的数字
把数组排成最小的数_牛客网
https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if len(numbers) == 0:
return ''
str_num = [str(i) for i in numbers]
for i in range(len(numbers)-1):
for j in range(i,len(numbers)):
if str_num[i]+str_num[j]>str_num[j]+str_num[i]:
str_num[i],str_num[j] = str_num[j],str_num[i]
return ''.join(str_num)
1.先要判断输入数组是否是空
2. 把原来的数组变成一个字符串数组
3.定义一个比较的规则:例如["3","32"]中332>323,所以要将3和32的位置调换,对于有三个数字的情况:对于有三个数字的情况: [3,32,321],首先将3和32进行调换,变为[32,3,321],然后这里用的是冒泡排序的做法,再将32与321进行组合,因为32132<32321,所以将32与321进行调换,接着,332>323,所以将3与32调换,最后[321,32,3],再用join方法组合,得到最小数字。
此处可能存在[0,0,0,0]这种情况,因此在输出的时候需要int(),然后可以再选择输出类型,str型或者int型