您的位置:首页 > 其它

leetcode largest number

2015-09-07 14:33 330 查看
视频分析:

http://v.youku.com/v_show/id_XMTMyOTM3NDcwMA==.html

题干:

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

思路分析:

这题论证方法严格来讲比较困难,不求甚解的话光写出代码来倒是不难。

[code]class Solution:
    # @param num, a list of integers
    # @return a string
    def largestNumber(self, num):
        num = sorted([str(x) for x in num], key = self.cmp_to_key(self.compare))
        ans = ''.join(num).lstrip('0')
        return ans or '0'
    def compare(self, a, b):
        return [1, -1][a + b > b + a]
    def cmp_to_key(self,mycmp):
        class K:
            def __init__(self, obj, *args):
                self.obj = obj
            def __lt__(self, other):
                return mycmp(self.obj, other.obj) < 0
            def __gt__(self, other):
                return mycmp(self.obj, other.obj) > 0
            def __eq__(self, other):
                return mycmp(self.obj, other.obj) == 0
            def __le__(self, other):
                return mycmp(self.obj, other.obj) <= 0
            def __ge__(self, other):
                return mycmp(self.obj, other.obj) >= 0
            def __ne__(self, other):
                return mycmp(self.obj, other.obj) != 0
        return K
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: