Largest Number(最大数字)

Largest Number

要求:给定一个非负整数的列表,排列它们形成最大的整数,考虑到整数的取值范围,最后的结果可采用字符串的形式表示。

例子:[2,256]=>2562,[824,8247]=>[8248247]

第一种方法:

刚开始做这道题的时候,整个思路停留在基数排序上,想着把这个排序过程,通过修改基数排序完成(太复杂了,想了好长时间)。

算法实现:

def largeNum(nums):

    nlen = len(nums)
    maxD = 0
    loop = 1

    for i in range(nlen):
        nums[i] = str(nums[i])
        if len(nums[i]) > maxD:
            maxD = len(nums[i])
    nums = sorted(nums,key=lambda x:x[0],reverse=True)
    shorted = []
    for i in range(nlen):
        strLen = len(nums[i])
        if strLen < maxD:
            loStr = '0'
            if nums[i][0] < nums[i][strLen-1]:
                loStr = nums[i][strLen-1]
            else:
                loStr = nums[i][0]
            nums[i] += loStr*(maxD-strLen)
            shorted.append(strLen)
        else:
            shorted.append(0)
    while loop < maxD:
        stPos = 0
        for i in  range(1,nlen):
            loch = loop - 1
            while loch >= 0 and nums[i][loch] == nums[i-1][loch]:
                loch -= 1
            if loch != -1:
                stPos = i
                continue
            key = shorted[i]
            value = nums[i]
            end = i
            while end > stPos and value[loop] > nums[end-1][loop]:
                nums[end] = nums[end-1]
                shorted[end] = shorted[end-1]
                end -= 1
            nums[end] = value
            shorted[end] = key
        loop += 1

    for i in range(nlen):
        if shorted[i] > 0:
            nums[i] = nums[i][0:shorted[i]]
    res = ''.join(nums)
    if res[0]=='0'
        return '0'
    return res
第二种方法:

想象其实,这就是一道字符串排序的题目,数字排序算法在这基本都适用。

算法实现:

def largeNum(nums):
    nlen = len(nums)
    nums=list(map(str,nums))
    for i in range(1,nlen):
        if nums[i]+nums[i-1] > nums[i-1] + nums[i]:
            key = nums[i]
            j = i
            while j > 0 and key + nums[j-1] > nums[j-1] + key:
                nums[j] = nums[j-1]
                j -= 1
            nums[j] = key
    res = ''.join(nums)
    if res[0] == '0':
        return '0'
    return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值