【剑指offer】把数组排成最小的数(python)
题目描述:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
解题思路:
本题我用到了简单排序的思想,经过比较之后选择出最小的,然后与当前的置换。
比较的方法,以 3和32为例
如果3 * 100 + 32 > 32 * 10 + 3,则32排在前面,很容易理解,3和32有两种排法,分别为332和323,显然32放前面的时候值比较小。
实现比较的代码:
for i in range(len(numbers)):
t = numbers[i]
m = i
for j in range(i + 1, len(numbers)):
if t * pow(10, len(str(numbers[j]))) + numbers[j] > numbers[j]* pow(10, len(str(t))) + t:
t = numbers[j]
m = j
if i != m:
temp = numbers[i]
numbers[i] = t
numbers[m] = temp
排序之后,将numbers数组中所有的元素组装起来即可,组装的代码:
length = 0
for ele in numbers:
length += len(str(ele))
r = 0
for ele in numbers:
r += ele * pow(10, length - len(str(ele)))
length -= len(str(ele))
完整代码:
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers:
return ""
for i in range(len(numbers)):
t = numbers[i]
m = i
for j in range(i + 1, len(numbers)):
if t * pow(10, len(str(numbers[j]))) + numbers[j] > numbers[j]* pow(10, len(str(t))) + t:
t = numbers[j]
m = j
if i != m:
temp = numbers[i]
numbers[i] = t
numbers[m] = temp
length = 0
for ele in numbers:
length += len(str(ele))
r = 0
for ele in numbers:
r += ele * pow(10, length - len(str(ele)))
length -= len(str(ele))
return r