【劍指offer】把陣列排成最小的數【python】
阿新 • • 發佈:2018-12-08
題目描述
輸入一個正整數陣列,把數組裡所有數字拼接起來排成一個數,列印能拼接出的所有數字中最小的一個。例如輸入陣列{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