【剑指offer】把数组排成最小的数【python】

题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值