题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
思路
使用排序的思想:如果3+321 > 321 + 3那么说明321应该在3的前面,使用快速排序,自己定义cmp函数
代码
class Solution:
def myCmp(self, num1, num2):
string1 = str(num1) + str(num2)
string2 = str(num2) + str(num1) #防止整数越界
if len(string1) < len(string2) or (len(string1) == len(string2) and string1 < string2):
return 1
return 0
def myQuickSort(self, numbers, start, end):
if start < 0 or end >= len(numbers) or start >= end:
return
low, high = start, end
key = numbers[low]
while low < high:
while low < high and self.myCmp(key, numbers[high]):
high -= 1
numbers[low] = numbers[high]
while low < high and not self.myCmp(key, numbers[low]):
low += 1
numbers[high] = numbers[low]
numbers[low] = key
self.myQuickSort(numbers, start, low - 1)
self.myQuickSort(numbers, low + 1, end)
def PrintMinNumber(self, numbers):
if numbers == []:
return ''
self.myQuickSort(numbers, 0, len(numbers) - 1)
string = ''
for num in numbers:
string += str(num)
return string