179. Largest Number

从昨天到现在,脑子真的很乱,基本不知道自己在干什么。

问题描述

Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.

问题分析

参考九章算法,即将原来的int数组转换为str数组后,比较任意两个x、y,如果x+y > y+x, 那么x应该放在y前面,这样就将这个问题变成了一个排序问题。

AC代码

class Solution:
    # @param {integer[]} nums
    # @return {string}
    def largestNumber(self, nums):
        strs = []
        for i in nums:
            strs.append(str(i))
        strs = sorted(strs, cmp=lambda x,y: 1 if x+y < y+x else -1)
        rst = ''.join(strs)
        i = 0
        while rst[0] == '0' and i < len(rst)-1:
            i += 1
        return rst[i:]

Runtime: 52 ms, which beats 90.00% of Python submissions.
语法知识点:sorted函数及lambda表达式。

你可能感兴趣的:(179. Largest Number)